Course
Singleton Class
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
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>
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.