类中的静态变量 需要通过类名.静态变量名 来修改 ;通过对象不能修改
python中如何统计一个类的实例化对象??
class Person:
#静态变量count,用于记录类被实例化的次数
count = mind = "有思想"
animal = "高级动物"
soul = "有思想"
def __init__(self ,country ,name ,sex ,age ,height ):
self.country = country
self.name = name
self.sex = sex
self.age = age
self.height = height
#类被实例化时,会自动调用__init__()方法
#类中的静态变量 需要类名.静态变量来修改
Person.count += def eat(self):
print("%s在吃饭" %self.name)
def sleep(self):
print("%s睡觉" %self.name)
def work(self):
print("%s工作……" %self.name) p1 = Person("中国","张三","男","","")
p2 = Person("中国","李四","男","","")
p3 = Person("美国","tanx","女","","")
p4 = Person(p1.country,p2.name,p3.sex,p2.age,p3.height) #通过类名 可以改变类中的静态变量
print(Person.count) #通过对象 不能改变类中的静态变量的值
p1.count =
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}