Build a Singleton
Advanced · Write the code · from __init__ vs __new__: What Actually Happens When You Create an Object
From the lesson: __init__ vs __new__: What Actually Happens When You Create an Object
When you write obj = MyClass(), it feels like one simple step. But under the hood, Python actually does two things: it creates the object, and then it initializes it. These are handled by two different methods - __new__ and __init__.
Read the lessonCreate a Logger class that implements the singleton pattern using __new__. No matter how many times you call Logger(), it should always return the same instance.
Add an __init__ that sets self.logs to an empty list only on the *first* initialization (use a guard flag).
Add a log(self, message) method that appends the message to self.logs.
Create two Logger instances, log a message on each, then print the length of logs from the first instance.
More __init__ and __new__ exercises
- Predict the Creation OrderAdvanced
- Subclass an Immutable TypeAdvanced
- Fix the Immutable SubclassAdvanced
- Build an Instance CacheAdvanced
All Python exercises · 50 practice problems · Metaprogramming quiz