Python - Singleton Class



Singleton Class

A singleton class is a class in which only one object can be created. This helps in optimizing memory usage when you perform some heavy operation, like creating a database connection.

Example

class SingletonClass:
   _instance = None
   
   def __new__(cls):
      if cls._instance is None:
         print('Creating the object')
         cls._instance = super(SingletonClass, cls).__new__(cls)
      return cls._instance
      
obj1 = SingletonClass()
print(obj1)

obj2 = SingletonClass()
print(obj2)

How Singleton Class Works?

When an instance of a Python class is declared, it internally calls the __new__() method. We override the __new__() method that is called internally by Python when you create an object of a class. It checks whether our instance variable is None. If the instance variable is None, it creates a new object, calls the super() method, and returns the instance variable that contains the object of this class.

If multiple objects are created, it becomes clear that the object is only created the first time; after that, the same object instance is returned.

Creating the object
<__main__.SingletonClass object at 0x000002A5293A6B50>
<__main__.SingletonClass object at 0x000002A5293A6B50>
Advertisements