在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 <module>
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 <module>
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 <module>
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'