gpt4 book ai didi

Python:带有双下划线的类

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:46 25 4
gpt4 key购买 nike

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

enter image description here

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

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

最佳答案

在类内部,标识符 __Singleton 正在获取 mangled .您最终会遇到问题,因为名称修改只发生在类内部(而不是外部)。因此,__Singleton 作为类名的含义不同于 __Singleton,当您在类套件中时。

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.

注意 mangling 的主要原因是因为它

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

还有:

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

因此,确实没有任何理由在名称中使用前导双下划线的类(类内方法调用不可能与类名发生冲突)。单个前导下划线足以向用户发出他们不应使用该类的信号:

... 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 __Foo(object):
def __init__(self):
super(globals()['__Foo'], self).__init__()

f = __Foo()
print f

关于Python:带有双下划线的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38645871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com