1.@classmethod
- class method is a method that is bound to the class, not a method that is bound to the class object (instance)
- The class method can access the state of the class because it can accept a parameter (cls) pointing to the class, rather than a parameter (self) pointing to the class instance.
- class method can modify the state of a class and apply it to all class instances.
class C(object): @classmethod def fun(cls, arg1, arg2, ...): .... fun: function that needs to be converted into a class method returns: a class method for function.
2.@staticmethod
- class method is also a method that is bound to class, not a method that is bound to class objects (instances)
- class method cannot access the status of the class
- class method exists in the class because it is a related function
class C(object): @staticmethod def fun(arg1, arg2, ...): ... returns: a static method for function fun.
3. Example
class A(object): value = 42 def m1(self): print() @classmethod def m2(cls): print() += 10 @staticmethod def m3(cls_instance): cls_instance.value -= 10 #The editor has created a Python learning exchange group: 531509025a = A() # a.m1 # <bound method A.m1 of <__main__.A object at 0x7fc8400b7da0>> a.m1() # 42 # m1()YesANormal methods in,Must be called on the instantiated object。If used directlyA.m1()Will getm1() missing 1 required positional argument: 'self'Error message。
This is the end of this article about the difference between @classmethod and @staticmethod in Python. For more related contents of Python @classmethod and @staticmethod, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!