1. Class methods
is a method owned by a class object and requires a decorator @classmethod to identify it as a class method, and for a class method, the first argument must be a class object, usually as the first parameter cls (but of course the variable with a different name as its first argument, but most people are accustomed to the ' CLS ' As the first parameter's name, it is best to use the ' CLS ', which can be accessed through instance objects and class objects.
class people: country = ‘china‘ #类方法,用classmethod来进行修饰 @classmethod def getCountry(cls): return cls.countryp = people()print p.getCountry() #可以用过实例对象引用print people.getCountry() #可以通过类对象引用
A class method can also be used to modify a class property:
ClassPeople:country =' China ' #类方法, decorated with Classmethod @classmethod def getcountry(CLS): return cls.country @ Classmethod def setcountry(cls,country): Cls.country = Countryp = People ()print p.getcountry () #可以用过实例对象引用Print people.getcountry () #可以通过类对象引用p. Setcountry (' Japan ') print p.getcountry () Print people.getcountry ()
The results show that access to class objects and instance objects has changed since the class method was used to modify the properties of the classes.
2. Static methods
Modifiers are required to @staticmethod modify them, and static methods do not require multiple-definition parameters
class people: country = ‘china‘ @staticmethod #静态方法 def getCountry(): return people.countryprint people.getCountry()
Summarize
From the definition of class and instance methods and static methods, it can be seen that the first parameter of a class method is the class object CLS, which must be the property and method of the class object that is referenced by the CLS, whereas the first argument of an instance method is the instance object self, which can be referred to by self as a class property, It may also be an instance property (which requires a specific analysis), but the instance property has a higher precedence in the case of class properties and instance properties with the same name. There is no need to define additional parameters in a static method, so referencing a class property in a static method must be referenced by a class object
Python Basics 2-static methods and class methods