Implementing Display
Easy
+2 pts
🎯 In Python, __str__ controls what users see when they print an object:
class Fraction:
def __init__(self, num, den):
self.num, self.den = num, den
def __str__(self):
return f"{self.num}/{self.den}"
print(Fraction(3, 4)) # 3/4
And __repr__ is for developers — what you see in the REPL or in debug output. Many Python developers conflate the two or only implement one.
Rust makes this separation explicit with two traits:
| Trait | Format specifier | Purpose | Python equivalent |
|---|---|---|---|
Debug | {:?} | Developer output | __repr__ |
Display | {} | User-facing output | __str__ |
You met Debug in the previous exercise — it can be derived with …
Login to see the full exercise.
Topics