Python 中的私有变量和方法
什么时候应该对 Python 中的私有成员和方法使用 _foo
(下划线)或 __bar
(双下划线)?
When should I use _foo
(an underscore) or __bar
(double underscore) for private members and methods in Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请注意,Python 中不存在“私有方法”之类的东西。双下划线只是名称修饰:
因此,当您需要进行修饰时,
__
前缀非常有用,例如,为了不与继承链上方或下方的名称发生冲突。对于其他用途,单下划线会更好,恕我直言。编辑,关于
__
上的混淆,PEP-8 对此非常明确:因此,如果您不希望子类意外地重新定义具有相同名称的自己的方法,请不要使用它。
Please note that there is no such thing as "private method" in Python. Double underscore is just name mangling:
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-8 is quite clear on that:So if you don't expect subclass to accidentally re-define own method with same name, don't use it.
双下划线。它以这样的方式破坏名称,以至于无法从类外部简单地通过
__fieldName
访问它,如果它们是私有的,这就是您想要开始的。 (尽管访问该字段仍然不是很难。)可以通过
_Foo__privateField
来访问它。但它尖叫着“我是私人的,别碰我”,这比什么都没有好。The double underscore. It mangles the name in such a way that it can't be accessed simply through
__fieldName
from 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.)It will be accessible through
_Foo__privateField
instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.双下划线。这破坏了这个名字。该变量仍然可以被访问,但这样做通常是一个坏主意。
使用单下划线表示半私有(告诉 python 开发人员“只有在绝对必须时才更改它”),使用双下划线表示完全私有。
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.
因为那是编码约定。
请参阅此处了解更多信息。
Because thats coding convention.
See here for more.