I am under the impression that, using Singleton pattern I can limit the number of instantiation of a class to one object. And keeping that in mind, have a look at the below code:
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 base1(object):
__metaclass__ = Singleton
class base2(base1):
pass
class base3(base1):
pass
class base4(base2):
pass
obj1 = base4()
obj2 = base4()
print obj1 is obj2 #prints True
obj3 = base3()
obj4 = base3()
print obj3 is obj4 #prints True
print obj1 is obj3 #prints False
So the final print statement prints a False. What could be the best way to go ahead in achieving the goal, "Always return the same base1 object no matter which sub class instantiates it".
Aucun commentaire:
Enregistrer un commentaire