Bird
0
0

What is the main difference between __str__ and __repr__ methods in Python?

easy📝 Conceptual Q2 of 15
Python - Magic Methods and Operator Overloading
What is the main difference between __str__ and __repr__ methods in Python?
A__str__ formats numbers; __repr__ formats strings
B__str__ returns bytes; __repr__ returns strings
C__str__ is for user-friendly output; __repr__ is for developer debugging
D__str__ is called automatically; __repr__ is not
Step-by-Step Solution
Solution:
  1. Step 1: Define __str__ and __repr__ roles

    __str__ provides a readable string for end users, while __repr__ provides a detailed string for developers, often for debugging.
  2. Step 2: Eliminate incorrect options

    __str__ and __repr__ both return strings, both can be called automatically, and neither is specifically for formatting numbers or strings only.
  3. Final Answer:

    __str__ is for user-friendly output; __repr__ is for developer debugging -> Option C
  4. Quick Check:

    User vs developer string = __str__ vs __repr__ [OK]
Quick Trick: __str__ is user-friendly; __repr__ is developer-focused [OK]
Common Mistakes:
  • Thinking __repr__ returns bytes
  • Believing __str__ is never called automatically
  • Mixing formatting roles with these methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes