initialization - Why Singleton in python calls __init__ multiple times and how to avoid it? -
i've implementation of singleton pattern in python, i've noticed init called, uselessly, everytime call myclass, despite same instance returned.
how can avoid it?
class test(object): def __init__(self, *args, **kwargs): object.__init__(self, *args, **kwargs) class singleton(object): _instance = none def __new__(cls): if not isinstance(cls._instance, cls): cls._instance = object.__new__(cls) return cls._instance class myclass(singleton): def __init__(self): print("should printed 1 time") self.x=test() pass = myclass() # prints: "should printed 1 time" b = myclass() # prints ( again ): "should printed 1 time" print(a,b) # prints: 0x7ffca6ccbcf8 0x7ffca6ccbcf8 print(a.x,b.x) # prints: 0x7ffca6ccba90 0x7ffca6ccba90
the problem __new__ doesn't return object, returns unitialized object on __init__ called afterwards.
you can't avoid @ all. can following(using metatypes):
class singleton(type): def __init__(self, name, bases, mmbs): super(singleton, self).__init__(name, bases, mmbs) self._instance = super(singleton, self).__call__() def __call__(self, *args, **kw): return self._instance class test(metaclass = singleton): # __metaclass__ = singleton # in python 2.7 def __init__(self, *args, **kw): print("only ever called once")
Comments
Post a Comment