并不是所有的屬性都可以被外部訪問的,這種不能被外部訪問的屬性稱為私有屬性。私有屬性是以雙下劃線'__'開頭的屬性。
# 類私有屬性 class Animal(object): __localtion = 'Asia' print(Animal.__localtion) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'Animal' has no attribute '__localtion'
# 實例私有屬性 class Animal(object): def __init__(self, name, age, localtion): self.name = name self.age = age self.__localtion = localtion dog = Animal('wangwang', 1, 'GuangDong') print(dog.name) # ==> wangwang print(dog.age) # ==> 1 print(dog.__localtion) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Animal' object has no attribute '__localtion'
在外部訪問私有屬性將會拋出異常,提示沒有這個屬性。
雖然私有屬性無法從外部訪問,但是,從類的內部是可以訪問的。私有屬性是為了保護類或實例屬性不被外部污染而設計的。
請給Animal類的__init__方法中添加name和age參數,并把age綁定到__age屬性上,看看外部是否能訪問到。
參考答案:
class Animal(object): def __init__(self, name, age): self.name = name self.__age = age cat = Animal('Kitty', '3') print(cat.name) print(cat.__age)
請驗證,完成請求
由于請求次數過多,請先驗證,完成再次請求
打開微信掃碼自動綁定
綁定后可得到
使用 Ctrl+D 可將課程添加到書簽
舉報