Python面向对象中的“私有化”
2018-05-12 18:49
501 查看
Python面向对象中的“私有化”
Python并不直接支持私有方式,而要靠程序员自己把握在外部进行特性修改的时机。
为了让方法或者特性变为私有(从外部无法访问),只要在它的名字前面加上双下划线即可。
由双下划线
__开始的属性在运行时被“混淆”,所以直接访问是不允许的。实际上,在 Python 带有双下划线的属性或方法并非正真意义上的私有,它们仍然可以被访问。
在类的内部定义中,所有以双下划线开始的名字都被“翻译”成前面加上单下划线和类名的形式。
示例:
>>> class TestObj(object): ... __war = "world" ... ... def __init__(self): ... self.__har = "hello" ... ... def __foo(self): ... print(self.__har + self.__war) ... ... ... >>> t = TestObj() >>> dir(t) # 拿到t里面的所有方法 ['_TestObj__foo', '_TestObj__har', '_TestObj__war', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getat tribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__ ', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] >>> t.__war Traceback (most recent call last): File "<input>", line 1, in <module> t.__war AttributeError: 'TestObj' object has no attribute '__war' >>> t.__har Traceback (most recent call last): File "<input>", line 1, in <module> t.__har AttributeError: 'TestObj' object has no attribute '__har' >>> t.foo() Traceback (most recent call last): File "<input>", line 1, in <module> t.foo() AttributeError: 'TestObj' object has no attribute 'foo' >>> t._TestObj__war 'world' >>> t._TestObj__har 'hello' >>> t._TestObj__foo() helloworld
相关文章推荐
- Python10--面向对象
- python 面向对象之添加功能
- python 面向对象初认识
- python学习笔记——6_面向对象
- 【Python】学习笔记九:面向对象拓展
- python 高级之面向对象初级
- 廖雪峰Python教程1轮还没学明白的(1) -- 面向对象高级编程 -- 定制类 -- 斐波那契数列
- < 笔记 > Python - 08 Python 面向对象高级编程(OOP Advanced Features)
- python 面向对象
- #python#面向对象练手+模仿Amazon的物流追踪显示
- Python学习--11 面向对象高级编程
- Python面向对象之类的定义与继承
- python通过面向对象程序设计方法 实现铅球运行轨迹的计算
- Python面向对象相关
- 大牛级别程序员带小白入门Python,花7天整理最全面向对象教程!
- 面向对象_python
- Python 面向对象总结
- python面向对象-理清object与type的关系
- python面向对象基本知识
- python面向对象思维导图