Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
String Representation Methods
📖 Scenario: You are creating a simple program to represent a book with its title and author. You want to show the book details in two ways: one for users and one for developers.
🎯 Goal: Build a Python class Book with two string representation methods: __str__ and __repr__. Use these methods to display the book details differently.
📋 What You'll Learn
Create a class called Book with title and author attributes
Add a __str__ method that returns a user-friendly string
Add a __repr__ method that returns a developer-friendly string
Create an instance of Book with exact title 'The Great Gatsby' and author 'F. Scott Fitzgerald'
Print the instance using print(book) to show the __str__ output
Print the instance using repr(book) to show the __repr__ output
💡 Why This Matters
🌍 Real World
String representation methods help show objects clearly in programs and debugging.
💼 Career
Understanding __str__ and __repr__ is important for writing readable and maintainable Python code.
Progress0 / 4 steps
1
Create the Book class with attributes
Create a class called Book with an __init__ method that takes title and author as parameters and assigns them to instance variables.
Python
Hint
Use def __init__(self, title, author): and assign self.title = title and self.author = author.
2
Add the __str__ method
Add a __str__ method to the Book class that returns a string in the format: "Title: {self.title}, Author: {self.author}".
Python
Hint
The __str__ method should return a formatted string with the title and author.
3
Add the __repr__ method
Add a __repr__ method to the Book class that returns a string in the format: "Book(title='{self.title}', author='{self.author}')".
Python
Hint
The __repr__ method should return a string that looks like how you create the object.
4
Create instance and print outputs
Create an instance called book of the Book class with title 'The Great Gatsby' and author 'F. Scott Fitzgerald'. Then print book and print repr(book).
Python
Hint
Use book = Book('The Great Gatsby', 'F. Scott Fitzgerald'), then print(book) and print(repr(book)).
Practice
(1/5)
1. Which method in Python is used to define the informal string representation of an object, typically for end users, and is called by the print() function?
easy
A. __init__
B. __repr__
C. __str__
D. __del__
Solution
Step 1: Understand the purpose of __str__
The __str__ method returns a readable string for users, used by print().
Step 2: Compare with __repr__
The __repr__ method returns a detailed string for developers, not usually for printing.
Final Answer:
__str__ -> Option C
Quick Check:
Informal string for print() = __str__ [OK]
Hint: Use __str__ for user-friendly print output [OK]
Common Mistakes:
Confusing __repr__ with __str__
Thinking __init__ controls string output
Assuming __del__ affects printing
2. Which of the following is the correct syntax to define the __repr__ method inside a Python class?
easy
A. def __repr__(self): self.return 'object info'
B. def repr(self): return 'object info'
C. def __repr__(self): print('object info')
D. def __repr__(self): return 'object info'
Solution
Step 1: Check method name and parameters
The method must be named __repr__ and take self as parameter.
Step 2: Verify return statement
__repr__ must return a string, not print or use invalid syntax.
Final Answer:
def __repr__(self): return 'object info' -> Option D
Quick Check:
Correct __repr__ syntax returns string [OK]
Hint: __repr__ must return a string, not print it [OK]
Common Mistakes:
Omitting underscores in __repr__
Using print instead of return
Wrong method name without underscores
3. What is the output of this code?
class Cat:
def __repr__(self):
return 'Cat()'
def __str__(self):
return 'A cute cat'
c = Cat()
print(c)
print(repr(c))
medium
A. A cute cat
Cat()
B. Cat()
A cute cat
C. A cute cat
A cute cat
D. Cat()
Cat()
Solution
Step 1: Understand print(c) calls __str__
The print(c) calls __str__, which returns 'A cute cat'.
Step 2: Understand print(repr(c)) calls __repr__
The repr(c) calls __repr__, which returns 'Cat()'.
The __repr__ method uses print() instead of returning a string, which is incorrect.
Step 2: Understand consequences
Because __repr__ returns None, printing the object calls __str__ but repr() would fail to give a string.
Final Answer:
__repr__ should return a string, not print it -> Option A
Quick Check:
__repr__ must return string, not print [OK]
Hint: 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)
5. 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
hard
A. return f"Book('{self.title}')"
B. return f"Book(title='{self.title}')"
C. return f"Book(title={self.title})"
D. return f"Book({self.title})"
Solution
Step 1: Understand __str__ output
The __str__ method returns a user-friendly string with the title.
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.
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.
Final Answer:
return f"Book(title='{self.title}')" -> Option B
Quick Check:
__repr__ returns constructor call string [OK]
Hint: __repr__ should return code to recreate object [OK]