Static methods are independent of instances of classes and classes. They are methods defined in the scope of classes. It can be called directly by classes and instances.
Both class methods and static methods must be defined by the decorator. The basic format is as follows:
@ Staticmethod
Def <function name> ():
# Do something
The basic format of the class method definition is:
@ Classmethod
Def <function name> (cls ):
# Do something
Different from the member method, the class method requires the cls parameter to be passed in, and cls indicates the class.
class Myclass():x='class';def __init__(self):self.x='instance';@ staticmethoddef staticmd():print 'static method';@classmethoddef classmd(cls):print cls.x;def inst(self):print self.x;
Class instances can access static methods, class methods, and member methods.
>>> Test = Myclass ()
>>> Test. staticmd ()
Static method
>>> Test. classmd ()
Class
>>> Test. inst ()
Instance
Class can access static methods and class methods, but cannot access member Methods
>>> Myclass. staticmd ()
Static method
>>> Myclass. classmd ()
Class
>>> Myclass. inst ()
TypeError: unbound method inst () must be called with Myclass instance as first argument (got nothing instead)
Static methods can be inherited. The following derived1 class inherits the Myclass class, And the derived1 class also has static methods. The instance of derived1 can directly call the staticmd () method.
Class derived1 (Myclass ):
Def _ init _ (self ):
Myclass. _ init _ (self );
>>> D = derived1 ()
>>> D. staticmd ()
Static method
Class methods can also be inherited. The instance class method of the class of the derived class automatically calls the class method of the derived class version to realize polymorphism. The following derived2 class inherits from Myclass. The derived2 class can call the class method classmd (cls). In this case, cls refers to derived2.
Class derived2 (Myclass ):
X = "derived2 ";
Def _ init _ (self ):
Myclass. _ init _ (self );
>>> D2 = derived2 ()
>>> D2.classmd ()
Derived2