A Singleton class is a class of which only one object can be created.
It is not allowed to create more than one object of that class.
This is usually helpful when you some heavy operation, like creating a database connection, in which creating a connection object each time you get a request would not be the right approach. Rather, you can use the same connection object to perform the database operations – this will save computation time as well as computation memory.
Now, let’s see how to create a Singleton class in Python.
class SingletonClass:_instance = Nonedef __new__(cls):if cls._instance is None:print('Creating the object')cls._instance = super(SingletonClass, cls).__new__(cls)return cls._instanceobj1 = SingletonClass()print(obj1)obj2 = SingletonClass()print(obj2)
Explanation:
__new__()
method that is called internally by Python when you create an object of a class.None
.super()
method.This can also be verified when we print
obj1
andobj2
, two objects that point to the same memory.
So, in this way, you can create a class and restrict the user to create only one object of that class.