class Animal(object):
__count=0
def __init__(self,name,age):
self.name=name
self.age=age
@classmethod
def get_count(cls):
return cls.__count
def set_count(cls,count):
cls.__count=count
Leo=Animal('herman',22)
print('name:{}\nage:{}'.format(Leo.name,Leo.age))
print('init count:',Leo.get_count())
Leo.set_count(98)
print('changed count:',Leo.get_count())
实例本身无count,get_count定义的是类方法,因此Leo.get_count()返回Animal的私有属性__count=0,set_count是实例方法对类无效,因此获取的__count 还是原本的0.
@classmethod 用于标识紧接着它的那一个方法
@classmethod
def get_count(cls):
return cls.__count
@classmethod
def set_count(cls,count):
cls.__count=count