Static methods are separate instances of classes and classes. It is a method defined in the class scope.
It can be called directly by classes and instances.
Both the class method and the static method are defined using adorners, and the basic format for the definition is:
@staticmethod
def <function name> ():
#do something
The basic format for class method definitions is:
@ Classmethod
def <function name> (CLS):
#do something
The class method differs from the member method in that it needs to pass in the number of cls,cls to represent the class.
Class Myclass (): X= ' class ';d ef __init__ (self): self.x= ' instance '; @ staticmethoddef staticmd ():p rint ' static method '; Classmethoddef CLASSMD (CLS):p rint Cls.x;def Inst (self):p rint self.x;
Instance of the class 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 not member methods
>>>myclass.staticmd ()
static method
>>>MYCLASS.CLASSMD ()
Class
>>>myclass.inst ()
Typeerror:unbound Method Inst () must is 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 a static method. An instance of derived1 can call the Staticmd () method directly
Class Derived1 (Myclass):
Def__init__ (self):
Myclass.__init__ (self);
>>>d=derived1 ()
>>>d.staticmd ()
static method
Class methods can also be inherited, and instances of classes of derived classes are interviewed by class methods. The class method of the derived class version number will be invoked on its own initiative to implement polymorphism.
The following Derived2 class inherits from the Myclass,derived2 class's ability to call the class method Classmd (CLS), at which time the CLS refers to Derived2.
Class Derived2 (Myclass):
x= "Derived2";
Def__init__ (self):
Myclass.__init__ (self);
>>>d2=derived2 ()
>>>D2.CLASSMD ()
Derived2
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
Python static methods and class methods