定義調(diào)用問(wèn)題:為什么set方法不起作用。1.一個(gè)@classmethod下,set在get后,不行;set在get前,可行。2.分別類定義set和get,可行。
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())
2021-11-21
實(shí)例本身無(wú)count,get_count定義的是類方法,因此Leo.get_count()返回Animal的私有屬性__count=0,set_count是實(shí)例方法對(duì)類無(wú)效,因此獲取的__count 還是原本的0.
2021-11-19
@classmethod 用于標(biāo)識(shí)緊接著它的那一個(gè)方法
2021-11-19
? ? @classmethod
? ? def get_count(cls):
? ? ? ? return cls.__count
? ? ? ?
? ? @classmethod ? ?
? ? def set_count(cls,count):
? ? ? ? cls.__count=count