I'm trying to implement class inherited singleton as described here (Method 2). Going over the question and the extensive chosen answer I tried to implement the following:
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not isinstance(cls._instance, cls):
cls._instance = object.__new__(cls, *args, **kwargs)
cls._instance._initialized = False
return cls._instance
class A(Singleton):
def __init__(self):
print "Init is called"
class B(Singleton):
def __init__(self):
print "Init is called"
As you may guess, whenever I create Class A
I get the same object, but __init__
is called. This is problematic as the Class A
can have all it's members changed due to this.
Doing:
a1 = A()
a2 = A()
print a1 == a2
Will result in:
>> Init is called
>> Init is called
>> True
This question poses a similar issue but I would prefer not to use the solution there as it doesn't include the inheritance and I have at least 2 classes that needs the Singleton
inheritance. I tried to implement the solution here but it didn't work. The solution here works but it involves changing Class A
and Class B
which I would prefer not to.
Is there a way to change the Singleton
implementation so that __init__
won't be called on every creation? (I can't use metaclasses as both A
and B
inherit other classes e.g. abstract classes with their own metaclasses).
Thank you