Editor

Predict the Creation Order

Advanced · Predict the output · 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

What does the following code print?

class Widget:
    def __new__(cls, name):
        print(f'new: {name}')
        instance = super().__new__(cls)
        return instance
    
    def __init__(self, name):
        print(f'init: {name}')
        self.name = name

w = Widget('button')
print(w.name)
# Type your predicted output

More __init__ and __new__ exercises

All Python exercises · 50 practice problems · Metaprogramming quiz