在Python中可以通過在屬性變量名前加上雙下劃線定義屬性為私有屬性,如例子:
復制代碼
代碼如下:
#! encoding=UTF-8
?
class A:
??? def __init__(self):
????????
??????? # 定義私有屬性
??????? self.__name = "wangwu"
????????
??????? # 普通屬性定義
??????? self.age = 19
????????
a = A()
?
# 正常輸出
print a.age
?
# 提示找不到屬性
print a.__name
執行輸出:
復制代碼
代碼如下:
Traceback (most recent call last):
? File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 19, in
??? print a.__name
AttributeError: A instance has no attribute '__name'
訪問私有屬性__name時居然提示找不到屬性成員而不是提示權限之類的,于是當你這么寫卻不報錯:
復制代碼
代碼如下:
#! encoding=UTF-8
?
class A:
??? def __init__(self):
????????
??????? # 定義私有屬性
??????? self.__name = "wangwu"
????????
??????? # 普通屬性定義
??????? self.age = 19
????????
?
a = A()
?
a.__name = "lisi"
print a.__name
執行結果:
1
lisi
在Python中就算繼承也不能相互訪問私有變量,如:
復制代碼
代碼如下:
#! encoding=UTF-8
?
class A:
??? def __init__(self):
????????
??????? # 定義私有屬性
??????? self.__name = "wangwu"
????????
??????? # 普通屬性定義
??????? self.age = 19
????????
?
class B(A):
??? def sayName(self):
??????? print self.__name
????????
?
b = B()
b.sayName()
執行結果:
復制代碼
代碼如下:
Traceback (most recent call last):
? File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 19, in
??? b.sayName()
? File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 15, in sayName
??? print self.__name
AttributeError: B instance has no attribute '_B__name'
或者父類訪問子類的私有屬性也不可以,如:
復制代碼
代碼如下:
#! encoding=UTF-8
?
class A:
??? def say(self):
??????? print self.name
??????? print self.__age
????????
?
class B(A):
??? def __init__(self):
??????? self.name = "wangwu"
??????? self.__age = 20
?
b = B()
b.say()
執行結果:
復制代碼
代碼如下:
wangwu
Traceback (most recent call last):
? File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 15, in
??? b.say()
? File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 6, in say
??? print self.__age
AttributeError: B instance has no attribute '_A__age'
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
