在Python中可以通過(guò)在屬性變量名前加上雙下劃線定義屬性為私有屬性,如例子:
復(fù)制代碼
代碼如下:
#! encoding=UTF-8
?
class A:
??? def __init__(self):
????????
??????? # 定義私有屬性
??????? self.__name = "wangwu"
????????
??????? # 普通屬性定義
??????? self.age = 19
????????
a = A()
?
# 正常輸出
print a.age
?
# 提示找不到屬性
print a.__name
執(zhí)行輸出:
復(fù)制代碼
代碼如下:
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'
訪問(wèn)私有屬性__name時(shí)居然提示找不到屬性成員而不是提示權(quán)限之類的,于是當(dāng)你這么寫(xiě)卻不報(bào)錯(cuò):
復(fù)制代碼
代碼如下:
#! encoding=UTF-8
?
class A:
??? def __init__(self):
????????
??????? # 定義私有屬性
??????? self.__name = "wangwu"
????????
??????? # 普通屬性定義
??????? self.age = 19
????????
?
a = A()
?
a.__name = "lisi"
print a.__name
執(zhí)行結(jié)果:
1
lisi
在Python中就算繼承也不能相互訪問(wèn)私有變量,如:
復(fù)制代碼
代碼如下:
#! 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()
執(zhí)行結(jié)果:
復(fù)制代碼
代碼如下:
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'
或者父類訪問(wèn)子類的私有屬性也不可以,如:
復(fù)制代碼
代碼如下:
#! 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()
執(zhí)行結(jié)果:
復(fù)制代碼
代碼如下:
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'
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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