本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
The meaning of a single- and a double-underscore before an object name in Python
在python中,对于私有成员和方法,我应该使用哪个foo(下划线)或u bar(双下划线)?
谢谢大家。我找到了另一个有用的话题。stackoverflow.com/questions/70528/…
更好:stackoverflow.com/questions/1301346/…
请注意,在python中没有"private method"这样的东西。双下划线只是名称错误:
>>> class A(object):
... def __foo(self):
... pass
...
>>> a = A()
>>> A.__dict__.keys()
['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__']
>>> a._A__foo()
因此,当需要发生损坏时(例如,不与继承链上下的名称冲突),__前缀非常有用。对于其他用途,单下划线会更好,imho。
编辑,关于__的混乱,pep-8非常清楚:
If your class is intended to be subclassed, and you have attributes
that you do not want subclasses to use, consider naming them with
double leading underscores and no trailing underscores. This invokes
Python's name mangling algorithm, where the name of the class is
mangled into the attribute name. This helps avoid attribute name
collisions should subclasses inadvertently contain attributes with the
same name.
Note 3: Not everyone likes name mangling. Try to balance the
need to avoid accidental name clashes with potential use by
advanced callers.
所以,如果您不希望子类意外地用相同的名称重新定义自己的方法,就不要使用它。
双下划线。它以这样一种方式管理名称,即它不能从类外部通过__fieldName简单地访问,如果它们是私有的,那么您首先要做的就是这样。(尽管进入现场并不困难。)
class Foo:
def __init__(self):
self.__privateField = 4;
print self.__privateField # yields 4 no problem
foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'
可通过_Foo__privateField进入。但它尖叫着"我是私人的,不要碰我",这比什么都没有要好。
双下划线。这个名字有点模糊不清。变量仍然可以访问,但这样做通常是一个坏主意。
对于半私有使用单下划线(告诉Python开发人员"只有在绝对必须更改的情况下才能更改它"),对于完全私有使用双下划线。
不太对。一个下划线意味着你正在篡改一个对象的未记录属性,而这个对象可能会发生变化,你很可能会破坏这个对象所维护的不变量,所以如果你决定破坏对象封装,你应该确切地理解你在做什么。
因为这是编码约定。更多信息请参见此处。
手术室问用哪一个。不是为什么。