Predict Singleton Behavior
Advanced · Predict the output · from Python Design Patterns: Factory, Strategy, Observer, and More
From the lesson: Python Design Patterns: Factory, Strategy, Observer, and More
Design patterns are proven recipes for solving common software problems. Think of them like architectural blueprints -- you wouldn't redesign plumbing from scratch for every house. Patterns give your code a shared vocabulary so other developers instantly understand your intent.
Read the lessonWhat does the following code print?
class Config:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.debug = False
return cls._instance
a = Config()
a.debug = True
b = Config()
print(b.debug)
print(a is b)class Config:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.debug = False
return cls._instance
a = Config()
a.debug = True
b = Config()
print(b.debug)
print(a is b)
More Design Patterns exercises
- Build a Shape FactoryAdvanced
- Strategy Pattern with FunctionsAdvanced
- Build an Event SystemAdvanced
- Implement the Decorator PatternAdvanced
- Template Method PatternAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz