Classmethod: Class Method
Staticmethod: Static Method
In python, both static and class methods can be accessed through class objects and class object instances. But the difference is:
- @ Classmethod is a function modifier, which indicates that the next class method is used. What we usually see is the instance method.The first parameter CLS of the class method, and the first parameter of the instance method is self, which indicates an instance of the class.
- A common object method requires at least one self parameter, representing a class object instance.
- The class method has the class variable CLS passed in, so that you can use CLs for some related processing.In addition, when a subclass is inherited and this class method is called, The passed-in class variable CLS is a subclass rather than a parent class..Class methods can be called through classes, just like C. F () is similar to the static method in C ++. It can also be called through an instance of the class, just like C (). F (), Here C () is written as this, and then it is an instance of the class.
- There is no static method. It is basically the same as a global function and rarely used.
Example 1:
>>> ClassA():
@ Staticmethod
Def Staticm ( ) :
Print 'Static'
Def Normalm ( Self ) :
Print 'Nomarl' , Self
@ Classmethod
Def Classm ( CLS ) :
Print 'Class' , CLS
> > > A1 = A ( )
> > > A1 . Normalm ( )
Nomarl < _ Main __ . A instance at 0x84dddec >
> > > A1 . Staticm ( )
Static
> > > A1 . Classm ( )
Class _ Main __ . A
> > > Type ( A )
< Type 'Classobj' >
> > > Type ( A1 )
< Type'Instance' >
Example 2:
Class A (object ):
@ Classmethod
Def cm (CLS ):
Print 'class method cm (CLS) Caller:', CLS. _ name __
@ Staticmethod
Def Sm ():
Print 'static method Sm () called'
Class B ():
Pass
A. cm ()
B. cm ()
A. Sm ()
B. Sm ()
Output:
Class Method cm (CLS) Caller:
Class Method cm (CLS) Caller: B
Static Method Sm () called
Static Method Sm () called
Connection: http://tiger-beach.blogspot.com/2008/04/python-classmethod-staticmethod.html