Bird
Raised Fist0

You want to create a class Book where print(book) shows the title nicely, but repr(book) shows a string that can recreate the object. Which implementation correctly achieves this?

hard🚀 Application Q15 of Q15
Python - Magic Methods and Operator Overloading
You want to create a class Book where print(book) shows the title nicely, but repr(book) shows a string that can recreate the object. Which implementation correctly achieves this?
class Book:
    def __init__(self, title):
        self.title = title

    def __str__(self):
        return f"Book titled '{self.title}'"

    def __repr__(self):
        # Which line below is correct?
        pass
Areturn f"Book('{self.title}')"
Breturn f"Book(title='{self.title}')"
Creturn f"Book(title={self.title})"
Dreturn f"Book({self.title})"
Step-by-Step Solution
Solution:
  1. Step 1: Understand __str__ output

    The __str__ method returns a user-friendly string with the title.
  2. Step 2: Create __repr__ that recreates object

    The __repr__ should return a string that looks like the constructor call with a keyword argument and quotes around the title.
  3. Step 3: Check options for correct syntax

    return f"Book(title='{self.title}')" returns Book(title='title') which can be used to recreate the object. Others miss quotes or keyword.
  4. Final Answer:

    return f"Book(title='{self.title}')" -> Option B
  5. Quick Check:

    __repr__ returns constructor call string [OK]
Quick Trick: __repr__ should return code to recreate object [OK]
Common Mistakes:
MISTAKES
  • Missing quotes around string in __repr__
  • Not using keyword argument in __repr__
  • Returning informal string in __repr__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes