Singletons
Used when we only want one instance throughout the entire program's lifespan.
class MySingleton(object): # object because we are inheriting from the baseclass object
_instance = None
def __new__(self):
if not self._instance:
self._instance = super(MySingleton, self
).__new__(self)
self.y = 10
return self._instance
x = MySingleton()What's happening above?
Storing definition of class in memory
when
MySingleton()is called, it checks to see if_instancehas been set, and if not, then we actually create an instance and create itResult: Only one instance is ever created
print(x.y)
>> 10
x.y = 20
z = MySingleton()
print(z.y)
>> 20Singleton as Decorator
Last updated
Was this helpful?