Bird
0
0

Identify the error in this class definition related to string representation methods:

medium📝 Debug Q14 of 15
Python - Magic Methods and Operator Overloading
Identify the error in this class definition related to string representation methods:
class Dog:
    def __str__(self):
        return 'Dog'
    def __repr__(self):
        print('Dog object')

print(Dog())
A__repr__ should return a string, not print it
B__str__ method is missing self parameter
Cprint(Dog()) should be print(Dog)
D__repr__ method name is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Check __repr__ method body

    The __repr__ method uses print() instead of returning a string, which is incorrect.
  2. Step 2: Understand consequences

    Because __repr__ returns None, printing the object calls __str__ but repr() would fail to give a string.
  3. Final Answer:

    __repr__ should return a string, not print it -> Option A
  4. Quick Check:

    __repr__ must return string, not print [OK]
Quick Trick: Always return string in __repr__, never print [OK]
Common Mistakes:
  • Using print instead of return in __repr__
  • Forgetting self parameter in methods
  • Confusing print(Dog()) with print(Dog)

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes