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

猜你喜欢

转载自www.cnblogs.com/bigtreei/p/9029528.html