实例讲解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的iOS自动化打包实例代码

Python的iOS自动化打包实例代码

前言 这段时间刚刚学习了一段时间的Python,加上自己是做iOS开发的,就想着用Python来做一个自动化打包,可以自动完成打包,上传到蒲公英,并且发送邮箱给测试人员. 一是可以减...

Python QQBot库的QQ聊天机器人

Python QQBot库的QQ聊天机器人

本文实例为大家分享了Python QQBot库的QQ聊天机器人的具体代码,供大家参考,具体内容如下 项目地址:https://github.com/pandolia/qqbot 1.安装...

Python使用Matplotlib实现雨点图动画效果的方法

Python使用Matplotlib实现雨点图动画效果的方法

本文实例讲述了Python使用Matplotlib实现雨点图动画效果的方法。分享给大家供大家参考,具体如下: 关键点 win10安装ffmpeg animation函数使用 update...

Ubuntu下使用python读取doc和docx文档的内容方法

读取docx文档 使用的包是python-docx 1. 安装python-docx包 sudo pip install python-docx 2. 使用python-docx...

python傅里叶变换FFT绘制频谱图

本文实例为大家分享了python傅里叶变换FFT绘制频谱图的具体代码,供大家参考,具体内容如下 频谱图的横轴表示的是 频率, 纵轴表示的是振幅 #coding=gbk...