Editor

Fix the Immutable Subclass

Advanced · Fix the bug · 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

This code tries to create a NamedTuple-like class by subclassing tuple, but the values aren't being set correctly. Fix it.

Expected output:

(10, 20)
10
20
class Point(tuple):
def __init__(self, x, y):
# Bug: trying to set values in __init__
# but tuple is immutable!
super().__init__((x, y))
@property
def x(self):
return self[0]
@property
def y(self):
return self[1]
p = Point(10, 20)
print(p)
print(p.x)
print(p.y)

More __init__ and __new__ exercises

All Python exercises · 50 practice problems · Metaprogramming quiz