Challenge - 5 Problems
String Representation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of __str__ vs __repr__
What is the output of the following code?
Python
class Fruit: def __init__(self, name): self.name = name def __str__(self): return f"Fruit: {self.name}" def __repr__(self): return f"Fruit('{self.name}')" f = Fruit('Apple') print(str(f)) print(repr(f))
Attempts:
2 left
💡 Hint
Remember __str__ is for user-friendly display, __repr__ is for developer-friendly output.
✗ Incorrect
The str() function calls __str__ which returns 'Fruit: Apple'. The repr() function calls __repr__ which returns 'Fruit('Apple')'.
❓ Predict Output
intermediate2:00remaining
Using __repr__ in a list
What is the output of this code?
Python
class Animal: def __init__(self, species): self.species = species def __repr__(self): return f"Animal('{self.species}')" animals = [Animal('Cat'), Animal('Dog')] print(animals)
Attempts:
2 left
💡 Hint
Lists use __repr__ of their elements when printed.
✗ Incorrect
When printing a list, Python calls __repr__ on each element. So it shows the string returned by __repr__ of each Animal.
🔧 Debug
advanced2:00remaining
Fix the __str__ method to avoid error
This code raises an error when printing the object. Which option fixes the error?
Python
class Book: def __init__(self, title): self.title = title def __str__(self): return 'Book title is ' + self.title.upper b = Book('Python 101') print(b)
Attempts:
2 left
💡 Hint
Check if you are calling the method or just referencing it.
✗ Incorrect
The error happens because self.title.upper is a method, not a string. You must call it with parentheses: self.title.upper().
🧠 Conceptual
advanced2:00remaining
Difference between __str__ and __repr__
Which statement best describes the difference between
__str__ and __repr__ methods in Python?Attempts:
2 left
💡 Hint
Think about who the string is for: user or developer.
✗ Incorrect
__str__ returns a friendly string for users, while __repr__ returns a detailed string useful for developers to identify the object.
❓ Predict Output
expert2:00remaining
Output of custom __repr__ with eval
What is the output of this code?
Python
class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point({self.x}, {self.y})" p = Point(3, 4) q = eval(repr(p)) print(p == q) print(q)
Attempts:
2 left
💡 Hint
Does eval(repr(p)) create an equal object? What about equality check?
✗ Incorrect
The repr returns 'Point(3, 4)', but eval tries to call Point(3, 4). Since Point constructor exists, q is a new object with same values but different identity. The default == compares identity, so p == q is False.