Editor

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 lesson

Create 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.

class Logger:
# Your singleton code here
pass
a = Logger()
b = Logger()
a.log('error 1')
b.log('error 2')
print(a is b)
print(len(a.logs))

More __init__ and __new__ exercises

All Python exercises · 50 practice problems · Metaprogramming quiz