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
1# 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.
After this program
If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.