In high-level languages such as Java and C #, we define static and static variables using static, so how do you define static and static variables in Python?
Python provides @classmethod and @staticmethod to define static methods, which are not quite clear at the moment of contact, and stack overflow provides a more understandable explanation, stack overflow answers.
But after reading or not quite understand, so I wrote an example:
Class Stclass (): d=1 #对象方法 def imethod (self): print (self) print ("instance method") #类方法 @classmethod def cmethod (CLS): print (CLS) print ("class method") #静态方法 @staticmethod def smethod (): print ("static method") SC = Stclass () Sc.imethod () Sc.cmethod () Sc.smethod ()
The results of the operation are as follows:
Then we can explain:
1, the instance method, which belongs to the object, the first parameter of the method is the current instance, owns the current class and all the attributes of the instance.
2, the class method, the instance belongs to the class, the first parameter of the method is the current class, you can do some processing of the class, if a static method and the class is concerned but not related to the instance, then use this method.
3, the static method, the instance belongs to the class, but the method has no parameters, that is, the method can not do the class processing, equivalent to the global method.
Class methods (@classmethod) and Static methods (@staticmethod) in the "developer Notes" python