python面试之名称修饰(name-mangling)

>>> class MyClass():
... def __init__(self):
... self.__superprivate = "Hello"
... self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute '__superprivate'
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}

foo :一种约定,Python内部的名字,用来区别其他用户自定义的命名,以防冲突. _foo :一种约定,用来指定变量私有.程序员用来指定私有变量的一种方式. __foo :这个有真正的意义:解析器用 _classname__foo 来代替这个名字,以区别和其他类相同的命名.


In [1]: class A:
   ...:     __p = 1
   ...:

In [2]: A.__p
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-f532f70a0839> in <module>()
----> 1 A.__p

AttributeError: type object 'A' has no attribute '__p'

In [6]: A._A__p
Out[6]: 1


In [7]: print(A.__dict__)
{'__module__': '__main__', '_A__p': 1, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}


# 在python中名称修饰用于私有成员,当一个成员名称以双下划线开头和不超过一个下划线结尾,  
# 它会在运行时被解释器重命名,以避免与任何子类中的方法产生命名冲突。重命名规则为"_类名+变量",如_A__p。

Ref: 1.https://en.wikipedia.org/wiki/Name_mangling#Python