Python面向對象中的“私有化”
阿新 • • 發佈:2018-05-12
hash delattr orm eof ssh most 外部 運行 RR
Python面向對象中的“私有化”
Python並不直接支持私有方式,而要靠程序員自己把握在外部進行特性修改的時機。
為了讓方法或者特性變為私有(從外部無法訪問),只要在它的名字前面加上雙下劃線即可。
由雙下劃線
__
開始的屬性在運行時被“混淆”,所以直接訪問是不允許的。實際上,在 Python 帶有雙下劃線的屬性或方法並非正真意義上的私有,它們仍然可以被訪問。
在類的內部定義中,所有以雙下劃線開始的名字都被“翻譯”成前面加上單下劃線和類名的形式。
示例:
>>> classTestObj(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
Python面向對象中的“私有化”