My idea is any one of the objects should exist for all the subclasses of a Singleton class. The code that I have been trying and the result matrix is given below. The matrix seems to be working fine in the case of subclasses. Am I going the wrong way? Did it get what happens in the case of a Parent class object and a subclass object?
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(
cls, *args, **kwargs)
return cls._instance
class A(Singleton):
def __new__(cls, *args, **kwargs):
super(A, cls).__new__(cls, *args, **kwargs)
class B(Singleton):
def __new__(cls, *args, **kwargs):
super(B, cls).__new__(cls, *args, **kwargs)
class C(B):
def __new__(cls, *args, **kwargs):
super(B, cls).__new__(cls, *args, **kwargs)
if __name__ == __main__ :
s1=Singleton()
s2=Singleton()
if(id(s1)==id(s2)):
print "Same"
else:
print "Different"
I got a result matrix for s1 and s2
|************ s2 **************************|
s1 |Singleton() |A() | B() | C() |
===========|==========================================|
Singleton()|Same |Different|Different|Different|
A() |Different |Same |Same |Same |
B() |Different |Same |Same |Same |
C() |Different |Same |Same |Same |