Singleton Pattern in Python
Level 5235 keystrokes
This implements the singleton pattern using __new__. Only one instance exists and all calls return the same object.
Python code
# Define singleton class1class Singleton: # Class variable to store the single instance2 _instance = None3 # __new__ controls instance creation4 def __new__(cls): # Check if instance already exists5 if cls._instance is None: # Create new instance using parent __new__6 cls._instance = super().__new__(cls) # Initialize instance attribute7 cls._instance.value = 0 # Return the single instance8 return cls._instance9 # Create first reference to singleton10a = Singleton()# Create second reference - same object11b = Singleton()# Modify value through first reference12a.value = 42# Print value through second reference - same value13print(b.value)# Verify both references point to same object14print(a is b)Output
42 True
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
_× 13.× 8(× 7)× 7=× 6:× 3