__str__ and __repr__
- Python course
- Intermediate
- Lesson 5/116
- 4 min
Learn representation with __str__ and __repr__.
The __str__ method
__str__ is the method that turns an instance into a human readable string. print() and str() call it. It must return a str.
Example: class Book:\n def __str__(self):\n return f"Book: {self.title}". Now print(b) shows Book: ...; otherwise you would see an ugly <Book object at 0x...>. __str__ produces the short text shown to the user.
The __repr__ method
__repr__ turns an instance into a developer representation. repr() and the interactive shell call it. Ideally it returns a string that can recreate the instance with eval.
Example: class Book:\n def __repr__(self):\n return f"Book(title={self.title!r})". Now repr(b) returns Book(title='...'). If __str__ is not defined, __repr__ is used as a fallback. While debugging, __repr__ is more informative.
Practice Add __str__ to the Book class
Define a class named Book. Add the method def __init__(self, title): and in the body write self.title = title. Also add the method def __str__(self): and write return f"Book: {self.title}". Then create an instance with b = Book("Les Mis") and print it with print(b).
Starter code
# Define the Book class with __init__ and __str__Sample solution
# Define the Book class with __init__ and __str__
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book: {self.title}"
b = Book("Les Mis")
print(b)Expected output
Book: Les Mis
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the __str__ signature
class Book:
def __str__(self):
return f"Book: {self.____}"
class Book:
def __str__(self):
return f"Book: {self.title}"
Explanation: You accessed the self.title attribute.
2 Match the two methods
| Term | Meaning |
|---|---|
__str__ |
Human readable |
__repr__ |
Developer repr |
print(b) |
Calls __str__ |
3 Which method does print(b) call?
- __str__ Correct answer
- __repr__
- __init__
- __len__
Explanation: print() calls the __str__ method first.