Python中的私有变量和方法

2024-05-14 18:27:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

对于Python中的私有成员和方法,我应该使用哪一个foo(下划线)或bar(双下划线)?


Tags: andofthenameinanobject成员
3条回答

请注意,在Python中没有“私有方法”这样的东西。双下划线只是名称混乱:

>>> 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开发人员“只有在绝对必须的情况下才能更改此值”),使用双下划线表示完全私有。

相关问题 更多 >

    热门问题