实例讲解Python中的私有属性
2023-06-13 09:15:43 时间
在Python中可以通过在属性变量名前加上双下划线定义属性为私有属性,如例子:
#!encoding=UTF-8
classA:
def__init__(self):
#定义私有属性
self.__name="wangwu"
#普通属性定义
self.age=19
a=A()
#正常输出
printa.age
#提示找不到属性
printa.__name
执行输出:
Traceback(mostrecentcalllast):
File"C:\Users\lee\Documents\AptanaStudio3Workspace\testa\a.py",line19,in<module>
printa.__name
AttributeError:Ainstancehasnoattribute"__name"
访问私有属性__name时居然提示找不到属性成员而不是提示权限之类的,于是当你这么写却不报错:
#!encoding=UTF-8
classA:
def__init__(self):
#定义私有属性
self.__name="wangwu"
#普通属性定义
self.age=19
a=A()
a.__name="lisi"
printa.__name
执行结果:
1
lisi
在Python中就算继承也不能相互访问私有变量,如:
#!encoding=UTF-8
classA:
def__init__(self):
#定义私有属性
self.__name="wangwu"
#普通属性定义
self.age=19
classB(A):
defsayName(self):
printself.__name
b=B()
b.sayName()
执行结果:
Traceback(mostrecentcalllast):
File"C:\Users\lee\Documents\AptanaStudio3Workspace\testa\a.py",line19,in<module>
b.sayName()
File"C:\Users\lee\Documents\AptanaStudio3Workspace\testa\a.py",line15,insayName
printself.__name
AttributeError:Binstancehasnoattribute"_B__name"
或者父类访问子类的私有属性也不可以,如:
#!encoding=UTF-8
classA:
defsay(self):
printself.name
printself.__age
classB(A):
def__init__(self):
self.name="wangwu"
self.__age=20
b=B()
b.say()
执行结果:
wangwu
Traceback(mostrecentcalllast):
File"C:\Users\lee\Documents\AptanaStudio3Workspace\testa\a.py",line15,in<module>
b.say()
File"C:\Users\lee\Documents\AptanaStudio3Workspace\testa\a.py",line6,insay
printself.__age
AttributeError:Binstancehasnoattribute"_A__age"
相关文章
- RPC协议及其python实例[通俗易懂]
- python中dtype的使用规范_Python numpy.dtype() 使用实例
- Python 获取窗口句柄,模拟鼠标点击
- json转字符串 python_Python读取json
- python模块有哪些_pycharm引入模块报错
- 【说站】python实例如何绑定属性
- 【说站】python创建实例中类属性的变化
- 【说站】python类属性和实例属性的区别
- 遗传算法的应用实例python实现_遗传算法Python解决一个问题
- python输出unicode编码_Python以utf8编码读取文件
- python lambda表达式举例_Python中lambda表达式[通俗易懂]
- python hexdump_笨办法学 Python · 续 练习 26:`hexdump`
- 如何利用python读excel数据_python在excel应用实例
- 最全Python操作excel代码,让你每天早下班两小时
- python递归函数讲解_Python递归函数实例讲解
- Python输入函数(input)如何使用?使用时需要注意什么?
- python-异常处理和错误调试-协程中的异常处理(一)
- Python类变量和实例变量(类属性和实例属性)
- Python类调用实例方法
- Python __slots__:限制类实例动态添加属性和方法
- Python多态实例详解编程语言
- Python 格式化字符详解编程语言
- 用Python仿写MSSQL 编程体验更有趣(python仿mssql)
- 在Python中简单调用MySQL(python调用mysql)
- Python高效编程技巧
- python连接oracle数据库实例
- python在windows下实现备份程序实例
- python私有属性和方法实例分析
- python计算书页码的统计数字问题实例