Python 中的私有变量和方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3385317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Private Variables and Methods in Python
提问by kurikintoki
Possible Duplicate:
The meaning of a single- and a double-underscore before an object name in Python
Which should I use _foo(an underscore) or __bar(double underscore) for private members and methods in Python?
对于 Python 中的私有成员和方法,我应该使用_foo(下划线)还是__bar(双下划线)?
回答by zneak
The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldNamefrom outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)
双下划线。它以一种不能简单地__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'
It will be accessible through _Foo__privateFieldinstead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.
它将_Foo__privateField改为通过访问。但它尖叫着“我是私人的,不要碰我”,这总比没有好。
回答by Daniel Kluev
Please note that there is no such thing as "private method" in Python. Double underscore is just name mangling:
请注意,Python 中没有“私有方法”这样的东西。双下划线只是名称修改:
>>> class A(object):
... def __foo(self):
... pass
...
>>> a = A()
>>> A.__dict__.keys()
['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__']
>>> a._A__foo()
So therefore __prefix is useful when you need the mangling to occur, for example to not clash with names up or below inheritance chain. For other uses, single underscore would be better, IMHO.
因此,__当您需要进行重整时,前缀非常有用,例如不与继承链上或下的名称发生冲突。对于其他用途,单下划线会更好,恕我直言。
EDIT, regarding confusion on __, PEP-8is quite clear on that:
编辑,关于混淆__,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.
如果您的类打算成为子类,并且您有不希望子类使用的属性,请考虑使用双前导下划线而不是尾随下划线命名它们。这会调用 Python 的名称修改算法,其中类的名称被修改为属性名称。如果子类无意中包含具有相同名称的属性,这有助于避免属性名称冲突。
注 3:并非每个人都喜欢名称修改。尝试平衡避免意外名称冲突的需要与高级呼叫者的潜在使用。
So if you don't expect subclass to accidentally re-define own method with same name, don't use it.
因此,如果您不希望子类意外地重新定义自己的同名方法,请不要使用它。
回答by user407896
Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.
双下划线。这破坏了名字。仍然可以访问该变量,但这样做通常是个坏主意。
Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.
对半私有使用单下划线(告诉 python 开发人员“只有在绝对必要时才更改它”),对完全私有使用双下划线。

