Python 類的私有屬性和 name mangling

Pep-8 (https://www.python.org/dev/peps/pep-0008)中給出了 一些 python 程序中命名的規範,其中有一條是 name mangling. java

在一個類中定義的屬性(不管是類屬性仍是實例屬性),若是是以 雙下劃線 (__) 開頭,那麼這個屬性是對外 (包括其子類中) 不可見的,相似於 java 中的 private 屬性。如何作到這一點呢, 畢竟 Python 並無真正意義上的訪問約束機制(好比 private, protected 修飾符)。Python 的作法是 name mangling, 姑且翻譯成名稱扭曲吧。具體作法是 若是你在某個類 clsA 中定義了一個屬性,名稱是  __a, 那麼 python 會把這個屬性改名成  _clsA__a, 可是改名後不影響你在內部使用,你在類的內部,仍是能夠使用  self.__a 來範圍。若是你非要在外部訪問 這個屬性,就只能使用 inst._clsA__a 來訪問。 (詳細的解釋能夠參考 pep-8: https://www.python.org/dev/peps/pep-0008/#naming-conventions)python

下面是示例:翻譯

>>> class A():
...     __clsattr = 'classattr'
...     def __init__(self):
...         self.__instattr = 5
...         self.__instattr2_ = 'ending underscore'
...
...     def get_instattr(self):
...         print(self.__instattr)
...
...     @classmethod
...     def get_clsattr(cls):
...         print(cls.__clsattr)
...
>>> A.get_clsattr()
classattr
>>> A.__clsattr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'A' has no attribute '__clsattr'
>>> A._A__clsattr
'classattr'
>>> obj = A()
>>> obj.get_instattr()
5
>>> obj.__instattr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute '__instattr'
>>> obj._A__instattr
5
>>> obj._A__instattr2_
'ending underscore'
相關文章
相關標籤/搜索