#coding: utf-8# describes the class orange: def __init__ (self, weight) of the Orange object: self.weight = weight #实例属性 def get_weight (self): print (self.weight) Class HostInfo: info = [] #类属性 def add_host (self, HOSTNAME, IP): self.info.append ({"hostname": hostname, "IP": IP}) def get_info (self): print (self.info) if __name__ == "__main__": o1 = orange ( 1.5) #橘子1 weight 1.5 o2 = orange (2.3) #橘子2 weight 2.3 o1.get_weight () #获取重量 o2.get_weight () #橘子1的重量是1.5, Orange 2 weighs 2.3, This so-called weight (data) is called a property, and the property is usually variable, #橘子类的每一个实例都会有重量This property, but the given data for each instance's properties will be different or the same h1 = hostinfo () #对象h1增加数据 h1.add_host ("PC", "192.168.1.2") h2 = hostinfo () #对象h2增加两条数据 h2.add_host ("PC", "192.168.1.2") h2.add_host ("PC", "192.168.1.2") h1.get_info () #不管是谁添加, everyone can get the host information, h2.get_info () # Conclusion: Class properties are shared across all instances, and instance properties belong only to the instance itself
Python object-oriented-class properties and instance properties