Python3 Singleton metaclass method not working

自闭症网瘾萝莉.ら 提交于 2019-11-28 03:22:49

问题


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?


回答1:


The metaclass syntax has changed in Python3. See the documentaition.

class MyClass(metaclass=Singleton):
    pass

And it works:

>>> MyClass() is MyClass()
True


来源:https://stackoverflow.com/questions/17237857/python3-singleton-metaclass-method-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!