In general, to use a method of a class, you need to instantiate an object before calling the method.
Instead of using @staticmethod or @classmethod, you can call it without instantiating it, directly from the class name. Method Name ().
This facilitates organizing the code, putting some functions that should belong to a class into that class, while facilitating the cleanliness of the namespace.
Since both @staticmethod and @classmethod can be called directly from the class name. Method Name (), what's the difference between them?
In terms of their use,
- @staticmethod does not need to represent the self of its own object and the CLS parameters of its own class, just as with a function.
- @classmethod also does not require the self parameter, but the first parameter needs to be a CLS parameter that represents its own class.
If you want to invoke some of the property methods of this class in @staticmethod, you can only direct the class name. The name of the property or class. Method name.
and @classmethod, because it holds the CLS parameter, can invoke the class's properties, class methods, instantiate objects, and so on, avoiding hard coding.
The code below.
1 classA (object):2Bar = 13 deffoo (self):4 Print 'Foo' 5 6 @staticmethod7 defStatic_foo ():8 Print 'Static_foo' 9 PrintA.barTen One @classmethod A defClass_foo (CLS): - Print 'Class_foo' - PrintCls.bar the cls (). Foo () - - A.static_foo () -A.class_foo ()
Output
Static_foo
1
Class_foo
1
Foo
Transferred from: http://blog.csdn.net/handsomekang/article/details/9615239
The function and difference of the flowing python-@staticmethod and @classmethod