I have the following two classes. Both raise an exception when using constructor a second time, as well as when using get_instance(). Now I'm no Python expert, so:
1) Which one is better?
2) What is the actual difference of using get_isntance() vs using constructor?
3) How do I ensure thread-safety? (Optional, I don't care about this as much right now)
The code:
class Logic:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(Logic, cls).__new__(cls)
return cls._instance
def __init__(self, **kwargs):
# Prevent reinitialization if an instance already exists
if hasattr(self, '_initialized') and self._initialized:
raise Exception("This class is a singleton!")
super(Logic, self).__init__(**kwargs)
self._initialized = True # Mark as initialized
@classmethod
def get_instance(cls, **kwargs):
return cls(**kwargs)
class Logic2:
_instance = None
def __init__(self, **kwargs):
# Prevent reinitialization if an instance already exists
if Logic2._instance:
raise Exception("This class is a singleton!")
super(Logic2, self).__init__(**kwargs)
Logic2._instance = self
@classmethod
def get_instance(cls, **kwargs):
return cls(**kwargs)