Python面向对象中的“私有化”

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

 

转载于:https://www.cnblogs.com/bigtreei/p/9029528.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值