Singleton Pattern in Python
Only one instance. Call the constructor twice, get the same object back. People overuse this.
IntermediateObject-Oriented ProgramsExample 23 of 25
singleton-pattern.py
Run in browser1# Program to implement a simple Singleton pattern23class Singleton:4 _instance = None56 def __new__(cls, *args, **kwargs):7 if cls._instance is None:8 cls._instance = super().__new__(cls)9 return cls._instance1011s1 = Singleton()12s2 = Singleton()1314print(s1 is s2)
Output
True
What's going on
Overriding __new__ ensures that only one instance of Singleton is ever created.