类私有化和模块私有化之间可能存在混淆。
A模块private以一个下划线开头
当使用import命令的from import *形式时,这样的元素不会被复制;但是,如果使用import 语法(see Ben Wilhelm's answer)
只需从问题示例的a.\u num中删除一个下划线,它就不会显示在使用from a import *语法导入a.py的模块中。
A类private以两个下划线开始(也称为d under,即d-ouble under score)
这样的变量的名称“mangled”包括类名等。
它仍然可以通过损坏的名称在类逻辑之外访问。
尽管名称管理可以作为防止未经授权访问的一种温和的预防设备,但它的主要目的是防止可能与祖先类的类成员发生名称冲突。
见Alex Martelli有趣但准确地引用了同意成人,因为他描述了关于这些变量的惯例。>>> 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 "", line 1, in
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
>>>