class privates 和 module privates 之间可能存在混淆 .
私有模块以 one underscore 开头
使用import命令的 from import * 形式时,不会复制此类元素;但是,如果使用 import 语法(see Ben Wilhelm's answer),则导入它
只需从使用 from a import * 语法导入a.py的模块中的问题's example and it won' t中显示的一个下划线中删除一个下划线 .
一个私人课程以 two underscores 开头(又名dunder,即d-ouble not-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
>>>