<p>类私有化和模块私有化之间可能存在混淆。</p>
<p>A<em>模块private</em>以一个下划线开头
当使用import命令的<code>from <module_name> import *</code>形式时,这样的元素不会被复制;但是,如果使用<code>import <moudule_name></code>语法(<a href="https://stackoverflow.com/a/13618522/166686">see Ben Wilhelm's answer</a>)<br/>
只需从问题示例的a.\u num中删除一个下划线,它就不会显示在使用<code>from a import *</code>语法导入a.py的模块中。</p>
<p>A<em>类private</em>以<strong>两个下划线开始(也称为d under,即d-ouble under score)<br/>
这样的变量的名称“mangled”包括类名等。<br/>
它仍然可以通过损坏的名称在类逻辑之外访问。<br/>
尽管名称管理可以作为防止未经授权访问的一种温和的预防设备,但它的主要目的是防止可能与祖先类的类成员发生名称冲突。
见Alex Martelli有趣但准确地引用了同意成人,因为他描述了关于这些变量的惯例。</p>
<pre><code>>>> class Foo(object):
... __bar = 99
... def PrintBar(self):
... print(self.__bar)
...
>>> myFoo = Foo()
>>> myFoo.__bar #direct attempt no go
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__bar'
>>> myFoo.PrintBar() # the class itself of course can access it
99
>>> dir(Foo) # yet can see it
['PrintBar', '_Foo__bar', '__class__', '__delattr__', '__dict__', '__doc__', '__
format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__
', '__subclasshook__', '__weakref__']
>>> myFoo._Foo__bar #and get to it by its mangled name ! (but I shouldn't!!!)
99
>>>
</code></pre>