I am new to Python and I am trying to learn this language by checking and creating examples of design patterns in Python.
I have a confusion with classic implementation of Singleton Pattern. Most of the articles out there mentions following implementation of Singleton as classic
class Singleton(object):
name = None
@staticmethod
def instance():
if '_instance' not in Singleton.__dict__:
Singleton._instance = Singleton()
return Singleton._instance
s1 = Singleton().instance();
s2 = Singleton().instance();
assert s1 is s2
But I am not fully convinced with this implementation because no where we are restricting users from creating multiple objects of Singleton class and I can still create an instance of this class by calling Singleton(). In Java, we prevent this by making constructor of class as Private.
Another implementation someone pointed me out is
class Singleton(object):
_instances = {}
def __new__(class, *args, **kwargs):
if class not in class._instances:
instance = super().__new__(class)
class.__instances[class] = instance
return class._instances[class]
And this has spinned my head off. Can someone explain me how this works?