计算一个类,实例化多少对象
class Count:
count = 0
def __init__(self):
Count.count = Count.count + 1 # Count.count = self.count + 1
obj1 = Count() # 跟全是obj1
obj2 = Count()
obj3 = Count()
obj4 = Count()
obj5 = Count()
obj6 = Count()
print(Count.count)
# 结果
# 6
再看
类名可以更改类中的静态变量值。但是对象,不能改变只能引用类中的静态变量
class Count:
count = 0
def __init__(self):
pass
# 通过类名可以更改类中的静态变量值
Count.count = 6
print(Count.__dict__)
# 结果
# {'__module__': '__main__', 'count': 6, '__init__': <function Count.__init__ at 0x00CB6F60>, '__dict__': <attribute '__dict__' of 'Count' objects>, '__weakref__': <attribute '__weakref__' of 'Count' objects>, '__doc__': None}
# 但是通过对象,不能改变只能引用类中的静态变量,如下
obj1 = Count()
print(obj1.count)
#结果
#0
obj1.count = 6 #这一步一做,就是该对象空间添加了count=6