Home > Article > Backend Development > Based on the difference between staticmethod and classmethod in python
This article mainly introduces the difference between staticmethod and classmethod based on python. It has certain reference value. Now I share it with everyone. Friends in need can refer to it
Examples
class A(object): def foo(self,x): print "executing foo(%s,%s)"%(self,x) @classmethod def class_foo(cls,x): print "executing class_foo(%s,%s)"%(cls,x) @staticmethod def static_foo(x): print "executing static_foo(%s)"%x a=A()
The above class has three functions, which are used as follows:
a.foo(1) # executing foo(<__main__.A object at 0xb7dbef0c>,1) ----------------------------------------------------------------- a.class_foo(1) # executing class_foo(<class '__main__.A'>,1) A.class_foo(1) # executing class_foo(<class '__main__.A'>,1) ----------------------------------------------------------------- a.static_foo(1) # executing static_foo(1) A.static_foo('hi') # executing static_foo(hi)
Difference
• The caller of foo() must be an instance of class A, the caller of class_foo() and static_foo() It can be either a class or an instance
• The parameters are different. The foo() parameters are self and other parameters. The class_foo() parameter uses the class (cls) to replace self. The static_foo() parameter only has parameters. There is no self and class (cls)
• foo() in a.foo(1) is bound to a, class_foo() is bound to the class, and static_foo() is bound to both None are bound, you can use print to view, as follows:
" print(a.foo) # <bound method A.foo of <main.A object at 0xb7d52f0c>> print(a.class_foo) # <bound method type.class_foo of <class 'main.A'>> print A.class_foo <bound method classobj.class_foo of > print(a.static_foo) # print(A.static_foo) # "
##Function
• Usage scenarios: classmethod is often used in some factory classes, which means it is used when inheriting in OOP. Staticmethod can generally be replaced by an external function, which cannot be changed when inherited, and C/JAVA The static methods in are very similar• It is conducive to organizing the code and at the same time conducive to the cleanliness of the namespaceThe above is the detailed content of Based on the difference between staticmethod and classmethod in python. For more information, please follow other related articles on the PHP Chinese website!