Difference between staticmethod and classmethod

后端 未结 28 2084
一整个雨季
一整个雨季 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:48

    Official python docs:

    @classmethod

    A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

    class C:
        @classmethod
        def f(cls, arg1, arg2, ...): ... 
    

    The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.

    It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

    Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.

    @staticmethod

    A static method does not receive an implicit first argument. To declare a static method, use this idiom:

    class C:
        @staticmethod
        def f(arg1, arg2, ...): ... 
    

    The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

    It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

    Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see classmethod() in this section.

提交回复
热议问题