您好,欢迎访问一九零五行业门户网

实例讲解Python中的私有属性

在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'
其它类似信息

推荐信息