python中如何統計一個類的例項化物件
阿新 • • 發佈:2018-10-31
類中的靜態變數 需要通過類名.靜態變數名 來修改 ;通過物件不能修改
python中如何統計一個類的例項化物件??
1 class Person: 2 #靜態變數count,用於記錄類被例項化的次數 3 count = 0 4 5 mind = "有思想" 6 animal = "高階動物" 7 soul = "有思想" 8 def __init__(self ,country ,name ,sex ,age ,height ): 9 self.country = country統計類的例項化物件程式碼10 self.name = name 11 self.sex = sex 12 self.age = age 13 self.height = height 14 #類被例項化時,會自動呼叫__init__()方法 15 #類中的靜態變數 需要類名.靜態變數來修改 16 Person.count += 1 17 18 def eat(self): 19 print("%s在吃飯" %self.name) 20 def sleep(self): 21 print("%s睡覺" %self.name) 22 def work(self): 23 print("%s工作……" %self.name) 24 25 p1 = Person("中國","張三","男","42","175") 26 p2 = Person("中國","李四","男","35","180") 27 p3 = Person("美國","tanx","女","21","160") 28 p4 = Person(p1.country,p2.name,p3.sex,p2.age,p3.height)29 30 #通過類名 可以改變類中的靜態變數 31 print(Person.count) 32 33 #通過物件 不能改變類中的靜態變數的值 34 p1.count = 8 35 print(Person.__dict__)
執行結果為:
4 {'__module__': '__main__', 'count': 4, 'mind': '有思想', 'animal': '高階動物', 'soul': '有思想',
'__init__': <function Person.__init__ at 0x00000000003C1E18>, 'eat': <function Person.eat at 0x000000000317AE18>,
'sleep': <function Person.sleep at 0x000000000317AEA0>, 'work': <function Person.work at 0x000000000317AF28>,
'__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}