This article mainly introduces the difference between Staticmethod and Classmethod based on Python, has a certain reference value, now share to everyone, the need for friends can refer to
Example
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, using the following:
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, and the caller of Class_foo () and Static_foo () can be either a class or an instance
• Different parameters, the foo () parameter is self and other parameters, the Class_foo () parameter uses the class (CLS) to replace the Self,static_foo () parameter only, no Self and Class (CLS)
Foo () in A.foo (1) is bound to A, class_foo () is bound to a class, and Static_foo () is not bound to either, and can be viewed using print, 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) # "
Role
• Usage Scenario: Classmethod is used in some factory classes, that is, when OOP inherits, Staticmethod can be replaced with external functions in general, which cannot be changed when inherited, and is similar to static methods in C++/java
• Facilitates the organization of code while facilitating the cleanliness of namespaces