I am trying to define Singleton class in python using a base class, following method 2 of this link, this is my code
class SingletonBase(object):
def __new__(cls, slots=None):
print(cls)
if not hasattr(cls, 'instance'):
print(object.__new__(cls))
cls.instance = object.__new__(cls, slots=None)
cls.instance.init_instance(slots=None)
#else:
return cls.instance
class Foo(SingletonBase):
def init_instance(self, slots=None):
self.slots = slots
print(slots)
def __init__(self):
print('execute init.')
,when I run on my python terminal
Foo()
i'm getting this error
AttributeError: type object 'Foo' has no attribute 'instance'
Please help, how to resolve this. I tried defining instance = None
at both SingletonBase and Foo class level, but nothing resolves.