实例讲解Python中的私有属性

yipeiwu_com7年前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 <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'

相关文章

常见的python正则用法实例讲解

下面列出Python正则表达式的几种匹配用法: 此外,关于正则的一切http://deerchao.net/tutorials/regex/regex.htm  1.测试正则表...

在Python中通过getattr获取对象引用的方法

getattr函数 (1)使用 getattr 函数,可以得到一个直到运行时才知道名称的函数的引用。 >>> li = ["Larry", "Curly"] >...

Python中的CSV文件使用"with"语句的方式详解

是否可以直接使用with语句与CSV文件?能够做这样的事情似乎很自然: import csv with csv.reader(open("myfile.csv")) as reade...

python实现飞机大战

python实现飞机大战

本文实例为大家分享了python实现飞机大战的具体代码,供大家参考,具体内容如下 实现的效果如下:   主程序代码如下: import pygame from plane_...

Python中的相关分析correlation analysis的实现

Python中的相关分析correlation analysis的实现

相关分析(correlation analysis) 研究两个或两个以上随机变量之间相互依存关系的方向和密切程度的方法。 线性相关关系主要采用皮尔逊(Pearson)相关系数r来度量连续...