@classmethod vs. @staticmethod in decorators

  

@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.

No comments:

Post a Comment