Python中的私有变量和方法 [英] Private Variables and Methods in Python

查看:213
本文介绍了Python中的私有变量和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
含义

Possible Duplicate:
The meaning of a single- and a double-underscore before an object name in Python

对于Python中的私有成员和方法,我应该使用_foo(下划线)还是__bar(双下划线)?

Which should I use _foo (an underscore) or __bar (double underscore) for private members and methods in Python?

推荐答案

请注意,没有私有方法"之类的东西.在Python中.双下划线只是名称修饰:

Please note that there is no such thing as "private method" in Python. Double underscore is just name mangling:

>>> 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.

编辑,关于__上的混淆, PEP-8 是对此很清楚:

EDIT, regarding confusion on __, PEP-8 is quite clear on that:

如果打算将您的类设为子类,并且您具有属性 不想使用子类的对象,请考虑使用它们命名 双前导下划线,无尾随下划线.这调用 Python的名称处理算法,其中类的名称为 改成属性名称. 这有助于避免属性名称 碰撞子类应无意中包含带有 相同的名字.

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.

注3:并非每个人都喜欢名字修饰.尝试平衡 需要避免意外的名称冲突,以免被潜在的使用 高级呼叫者.

Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.

因此,如果您不希望子类意外地用相同的名称重新定义自己的方法,请不要使用它.

So if you don't expect subclass to accidentally re-define own method with same name, don't use it.

这篇关于Python中的私有变量和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆