看不懂,參考答案為什么要這樣編輯?有沒(méi)有大神指導(dǎo)一下?
class Animal(object):
? ? def __init__(self, name, age, localtion):
? ? ? ? self.__name = name
? ? ? ? self.__age = age
? ? ? ? self.__localtion = localtion
? ? def set_name(self, name):
? ? ? ? self.__name = name
? ? def get_name(self):
? ? ? ? return self.__name
? ? def set_age(self, age):
? ? ? ? self.__age = age
? ? def get_age(self):
? ? ? ? return self.__age
? ? def set_localtion(self, localtion):
? ? ? ? self.__localtion =localtion
? ? def get_localtion(self):
? ? ? ? return self.__localtion
2021-10-12
可以這樣寫(xiě)
class Animal():
? ? def __init__(self,name,age,location):
? ? ? ? self.__name=name
? ? ? ? self.__age=age
? ? ? ? self.__location=location
? ??
? ? def get_hs(self):
? ? ? ? return 'name={},age={},location={}'.format(self.__name,self.__age,self.__location)
dog=Animal('wangcai',2,'HuNan')
cat=Animal('MiMi',1,'BeiJing')
print(dog.get_hs())
print(cat.get_hs())
2021-10-09
該Animal類(lèi)中有3個(gè)實(shí)例屬性,分別是name,age和location,并且這3個(gè)屬性都是帶雙下劃線(xiàn)(__)前綴的,說(shuō)明是私有屬性。私有屬性在類(lèi)的外部不能被直接訪(fǎng)問(wèn),但可以在類(lèi)的內(nèi)部直接訪(fǎng)問(wèn),所以定義了六個(gè)方法分別獲取(get)和設(shè)置(set)這三個(gè)私有屬性的值,在類(lèi)的外部可以通過(guò)這六個(gè)方法分別獲取或設(shè)置實(shí)例中這3個(gè)屬性的值。__init__實(shí)例方法是構(gòu)造函數(shù),在創(chuàng)建實(shí)例的時(shí)候可以方便同時(shí)設(shè)置實(shí)例的屬性的初始值。