oursolutionarchitectoursolutionarchitect
  • Python Questions and Answers
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
    • Selected Reading
    • Q&A

    Python - Singleton Class


    A Singleton class is a class of 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)
    

    This is how the above code works −

    When an instance of a Python class 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 and call 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>