Editor

Subclass an Immutable Type

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 class ClampedInt that subclasses int. It should clamp values to be between 0 and 255 (inclusive). Values below 0 become 0, values above 255 become 255.

Since int is immutable, you must use __new__ to set the value.

Print the results for ClampedInt(-50), ClampedInt(100), and ClampedInt(999).

class ClampedInt(int):
# Your code here
pass
print(ClampedInt(-50))
print(ClampedInt(100))
print(ClampedInt(999))

More __init__ and __new__ exercises

All Python exercises · 50 practice problems · Metaprogramming quiz