Singleton Pattern
Demonstrate a simple Singleton pattern implementation in Python.
IntermediateTopic: Object-Oriented Programs
Python Singleton Pattern Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to implement a simple Singleton pattern
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(s1 is s2)Output
True
Understanding Singleton Pattern
Overriding __new__ ensures that only one instance of Singleton is ever created.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.