Bird
0
0

You want to create a class that returns a string showing the object's name and age when printed, but a detailed representation for debugging. Which methods should you implement?

hard📝 Application Q8 of 15
Python - Magic Methods and Operator Overloading
You want to create a class that returns a string showing the object's name and age when printed, but a detailed representation for debugging. Which methods should you implement?
AImplement only __str__ for both outputs
BImplement only __repr__ for both outputs
CImplement __str__ for name and age; __repr__ for detailed info
DImplement __init__ to return strings
Step-by-Step Solution
Solution:
  1. Step 1: Understand roles of __str__ and __repr__

    __str__ is for user-friendly output (like name and age), __repr__ is for detailed debugging info.
  2. Step 2: Choose correct implementation strategy

    Implementing both methods separately allows different outputs for print() and debugging.
  3. Final Answer:

    Implement __str__ for name and age; __repr__ for detailed info -> Option C
  4. Quick Check:

    Use __str__ for user, __repr__ for debug [OK]
Quick Trick: Use __str__ for users, __repr__ for debugging details [OK]
Common Mistakes:
  • Using only __repr__ for all outputs
  • Using __init__ to return strings
  • Ignoring difference between __str__ and __repr__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes