Bird
Raised Fist0

Find the bug in this code snippet:

medium📝 Debug Q7 of Q15
Python - Magic Methods and Operator Overloading
Find the bug in this code snippet:
class Book:
    def __repr__(self):
        return Book(title)

b = Book()
ABook(title) is undefined; should return a string
BMissing __str__ method
CClass Book must inherit from object explicitly
DNo bug, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Analyze __repr__ return value

    The __repr__ method must return a string, but here it returns Book(title), which is invalid because title is undefined and it's not a string.
  2. Step 2: Identify the error

    Returning a non-string and using undefined variable causes a NameError and incorrect behavior.
  3. Final Answer:

    Book(title) is undefined; should return a string -> Option A
  4. Quick Check:

    __repr__ must return string, not object [OK]
Quick Trick: __repr__ must return a string, not an object [OK]
Common Mistakes:
MISTAKES
  • Returning objects instead of strings in __repr__
  • Assuming __str__ is mandatory
  • Thinking inheritance from object is required explicitly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes