class animal(object):
__count=0
def __init__(self,name,age):
self.name=name
self.age=age
animal.__count+=1
@classmethod
def get_count(cls):
return cls.__count
dog=animal('wangcai',2)
cat=animal('tom',3)
count=animal.get_count()
print(count)
#结果为2
实例的属性定义函数中也不能直接调用私有的类属性,需要加一个类方法,在实例的属性定义中:
class Animal(object):
__count=0
def __init__(self,name,age):
self.name=name
self.age=age
Animal.set_count()
@classmethod
def set_count(cls):
cls.__count+=1
@classmethod
def get_count(cls):
return cls.__count
dog=Animal('Wangwang',15)
cat=Animal('set',16)
print(Animal.get_count())
#答案为2