Reference: http://blog.csdn.net/handsomekang/article/details/9615239
In general, to use a method of a class, you need to instantiate an object before calling the method.
As we have defined a
Class A ():
Def __init__ ():
Print "A"
Def show ():
Print "Test"
A = ClassA ()
A.show ()
Using @staticmethod or @classmethod, you can do so without instantiating the direct class name. Method name () to invoke.
After modification:
Class A ():
Def __init__ ():
Print "A"
@staticmthod
Def show ():
Print "Test"
A.show ()
Since both @staticmethod and @classmethod can be directly class names. The method name () is invoked, so what's the difference between them? In terms of their use,
@staticmethod do not need to represent the CLS parameters of self and its own class for the object itself, as with functions. The self parameter is not required for @classmethod, but the first argument needs to be the CLS parameter representing its own class.
If you want to call some property methods of this class in @staticmethod, you can only direct the class name. property name or class name. Method Name.
@classmethod because it holds CLS parameters, you can invoke the properties of the class, the method of the class, instantiate the object, and so on, to avoid hard coding.
The code below.
[Python]View plain Copy class A (object): bar = 1 def foo (self): print ' foo ' @staticmethod def Static_foo (): print ' Static_foo ' Print A.bar @classmethod def class_foo (CLS): print ' Class_foo ' Print Cls.bar cls (). Foo () A.static_foo () A.class_foo () output
Static_foo
1
Class_foo
1
Foo
This is good for organizing code, putting some functions that should belong to a class into that class, while facilitating the cleanliness of namespaces.