mercredi 6 mai 2020

python3 singleton pattern that doesn't

The below is an attempt to implement Singleton in python 3 but it doesn't appear to work. When I instantiate, the _instance is always None and both instances (a and b) have different addresses in memory - why?

class Singleton(object):
    _instance = None

    def __call__(self, *args, **kwargs):
        if self._instance is None:
            self._instance = super().__call__(*args, **kwargs)
        return self._instance

    def __init__(self, *args, **kwargs):
        print(self._instance, self)


a = Singleton()
b = Singleton()
(None, <__main__.Singleton object at 0x7f382956c190>)
(None, <__main__.Singleton object at 0x7f382956c410>)

Aucun commentaire:

Enregistrer un commentaire