Python3 Singleton元类方法不起作用 [英] Python3 Singleton metaclass method not working
本文介绍了Python3 Singleton元类方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到了许多在Python中制作单例的方法,并且尝试在Python 3.2(Windows)中使用元类实现,但似乎并没有返回我的单例类的相同实例.
I saw a lot of methods of making a singleton in Python and I tried to use the metaclass implementation with Python 3.2 (Windows), but it doesn"t seem to return the same instance of my singleton class.
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class MyClass(object):
__metaclass__ = Singleton
a = MyClass()
b = MyClass()
print(a is b) # False
我现在使用的装饰器实现正在运行,但是我想知道该实现有什么问题吗?
I use the decorator implementation now which is working, but I'm wondering what is wrong with this implementation?
推荐答案
The metaclass syntax has changed in Python3. See the documentaition.
class MyClass(metaclass=Singleton):
pass
它有效:
>>> MyClass() is MyClass()
True
这篇关于Python3 Singleton元类方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文