<h2>单下划线</h2>
<p>在类中,带有前导下划线的名称只是为了向其他程序员表明属性或方法是私有的。不过,名字本身并没有什么特别之处。</p>
<p>引用<a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP-8</a>:</p>
<blockquote>
<p>_single_leading_underscore: weak "internal use" indicator. E.g. <code>from M import *</code> does not import objects whose name starts with an underscore.</p>
</blockquote>
<h2>双下划线(名称损坏)</h2>
<p>来自<a href="https://docs.python.org/3/tutorial/classes.html#private-variables" rel="noreferrer">the Python docs</a>:</p>
<blockquote>
<p>Any identifier of the form <code>__spam</code> (at least two leading underscores, at most one trailing underscore) is textually replaced with <code>_classname__spam</code>, where <code>classname</code> is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes. </p>
</blockquote>
<p>以及同一页的警告:</p>
<blockquote>
<p>Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private.</p>
</blockquote>
<h2>示例</h2>
<pre><code>>>> 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!'}
</code></pre>