Get The Most Affordable Hosting in the World!

Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.

Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!

Get Started Now!

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>




The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.
Bu cavab sizə kömək etdi? 1 istifadəçi bunu faydalı hesab edir (1 səs)