Python: class 带双下划线

Python: class with double underscore

我正在关注此 link 并尝试使用 Metaclass 创建一个单例 class。但是,我想对这个单例 class 进行一些内部调整,并希望用户使用另一个 class(我们称之为 MySingleton(__Singleton))。所以我决定将其设为私有,但出现以下错误。

我的唯一目的是防止__Singleton在外面被使用。我怎样才能做到这一点?

另外,在 classes 中使用双下划线是一种好习惯吗?

class 定义中带有两个前导下划线的每个名称都会被破坏,因此 __Singleton 变为 _Singleton__Singleton。为明确起见,某些 class 不应公开使用 one 下划线。

在 class 中,标识符 __Singleton 正在变为 mangled。您最终会遇到问题,因为名称修改只发生在 classes 内部(而不是外部)。所以 __Singleton 作为 class 名称的含义不同于 __Singleton 当你在 class 套房内时。

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

请注意,处理的主要原因是因为它

... is helpful for letting subclasses override methods without breaking intraclass method calls.

还有:

... to avoid name clashes of names with names defined by subclasses

因此,确实没有任何理由在名称中使用前导双下划线的 class(intraclass 方法调用不可能与 class 名字)。一个前导下划线足以向用户发出他们不应该使用 class:

的信号

... a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.


我不建议这样做,但如果您真的想要它工作,您可以使用globals查找class:

class __Foo(object):
    def __init__(self):
        super(globals()['__Foo'], self).__init__()

f = __Foo()
print f

Python没有private variables;它们都可以从外部访问。

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Python Cookbook 提供了一个 Singleton class 可以被其他 类 继承成为单例。