Difference between staticmethod and classmethod

后端 未结 28 2159
一整个雨季
一整个雨季 2020-11-21 06:11

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?

28条回答
  •  一生所求
    2020-11-21 06:33

    You might want to consider the difference between:

    class A:
        def foo():  # no self parameter, no decorator
            pass
    

    and

    class B:
        @staticmethod
        def foo():  # no self parameter
            pass
    

    This has changed between python2 and python3:

    python2:

    >>> A.foo()
    TypeError
    >>> A().foo()
    TypeError
    >>> B.foo()
    >>> B().foo()
    

    python3:

    >>> A.foo()
    >>> A().foo()
    TypeError
    >>> B.foo()
    >>> B().foo()
    

    So using @staticmethod for methods only called directly from the class has become optional in python3. If you want to call them from both class and instance, you still need to use the @staticmethod decorator.

    The other cases have been well covered by unutbus answer.

提交回复
热议问题