Frage

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?

War es hilfreich?

Lösung

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

class MyClass(metaclass=Singleton):
    pass

And it works:

>>> MyClass() is MyClass()
True
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top