The class method exists in order to modify the class properties.
code example:
class people (object): address = "Shandong" #类属性 #实例方法 def __init__ (self): self.name = "Xiaowang" # Instance properties self.age = #实例属性 #类方法 @classmethod def setnewaddress (CLS): cls.address = "Inner Mongolia" #可以通过类名的方式来获取类属性 #但是不能通过类名获取实例属性 #类对象, you can call the Class property directly, or you can call the class method #但是类对象 directly, disallow the invocation of the instance property, and do not allow the invocation of the instance method #如果是一个实例对象 #它可以获取实例属性和类属性的值, but only instance properties can be modified, class properties cannot be modified #他还可以调用实例方法和类方法xiaoming = people () Xiaoming.setnewaddress () print (people.address) execution result: Inner Mongolia
code Example 2:
Class Animal (object): def __init__ (self, name = "Animal", color = "white"): self.name = name Self.color = Colorclass Horse (Animal): horsenum = 0 #类属性 def __init__ (self, name, color = ""): super (). __INIT__ (name) Self.sethorsenum () @classmethod def sethorsenum (CLS): cls.horsenum + = 1bailongma = Horse ("White Dragon Horse") print ( Bailongma.name) print (bailongma.color) print (bailongma.horsenum) Chituma = Horse ("Red Rabbit Horse") print (chituma.name) print ( Chituma.color) print (chituma.horsenum) execution result: White Dragon horse white 1 red rabbit horse White 2
Class methods and Class properties