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中没有“私有方法”这样的东西。双下划线只是名称混乱:
因此,
__
前缀在需要发生损坏时非常有用,例如不与继承链上下的名称冲突。对于其他用途,单下划线会更好,IMHO。编辑,关于
__
上的混淆,PEP-8非常清楚:因此,如果您不希望子类意外地用相同的名称重新定义自己的方法,请不要使用它。
双下划线。它以这样一种方式损坏名称,以至于不能简单地通过类外部的
__fieldName
来访问它,如果它们是私有的,这就是您希望从它们开始的地方。(尽管进入这个领域仍然不是很困难。)它可以通过
_Foo__privateField
访问。但它尖叫着“我是私人,不要碰我”,这比什么都不做要好。双下划线。弄乱了名字。变量仍然可以访问,但这样做通常是个坏主意。
使用单下划线表示半私有(告诉python开发人员“只有在绝对必须的情况下才能更改此值”),使用双下划线表示完全私有。
相关问题 更多 >
编程相关推荐