Example
?
12345678910111213 |
class A (object): def foo (self,x): print "executing foo (%s,%s)"% (self,x) @classmethod &NBSP;&NBSP; def Class_foo (cls,x): &NBSP;&NBSP;&NBSP;&NBSP; print "executing Class_foo (%s,%s)"% (cls,x) &NBSP;&NBSP; @staticmethod &NBSP;&NBSP; def Static_foo (x): print "executing Static_foo (%s)"%x < Code class= "XHTML Plain" >a=a () |
The above class has three functions, using the following:
?
123456789101112131415161718 |
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
? Parameters, the foo () parameter is self and other arguments, the Class_foo () parameter uses the class (CLS) to replace Self,static_foo (), and only the parameters, 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:
?
123456789101112131415 |
" Code class= "XHTML Plain" >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 < Code class= "XHTML keyword" >bound method Classobj.class_foo of; < Code class= "XHTML Plain" >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
The above is based on the Python Staticmethod and Classmethod Differences (detailed) is the small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we support the script home.
Based on the difference between Staticmethod and Classmethod in Python (detailed)