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