I was looking over the Singleton design pattern in Python here: http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html
class OnlyOne:
class __OnlyOne:
def __init__(self, arg):
self.val = arg
def __str__(self):
return repr(self) + self.val
instance = None
def __init__(self, arg):
if not OnlyOne.instance:
OnlyOne.instance = OnlyOne.__OnlyOne(arg)
else:
OnlyOne.instance.val = arg
def __getattr__(self, name):
return getattr(self.instance, name)
I was thinking that in Java the Singleton pattern is implemented using a private constructor.
However, there is no private constructor in the code above and as I understand it, there are no private methods in Python.
So if you want to implement Singleton, how can you prevent someone from instantiating a class multiple times?