看不懂,參考答案為什么要這樣編輯?有沒有大神指導一下?
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
可以這樣寫
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類中有3個實例屬性,分別是name,age和location,并且這3個屬性都是帶雙下劃線(__)前綴的,說明是私有屬性。私有屬性在類的外部不能被直接訪問,但可以在類的內部直接訪問,所以定義了六個方法分別獲取(get)和設置(set)這三個私有屬性的值,在類的外部可以通過這六個方法分別獲取或設置實例中這3個屬性的值。__init__實例方法是構造函數,在創建實例的時候可以方便同時設置實例的屬性的初始值。