__repr__ and __str__ in Python
Level 4272 keystrokes
This shows __repr__ and __str__ for different string representations. __repr__ is for developers, __str__ is for end users.
Python code
# Define a Book class with two string representations1class Book: # The constructor takes a title and an author2 def __init__(self, title, author): # Store both values as instance attributes3 self.title = title4 self.author = author5 # __repr__: an unambiguous form for developers, used by repr()6 def __repr__(self): # Return text that looks like the constructor call7 return f"Book('{self.title}', '{self.author}')"8 # __str__: a readable form for users, used by str() and print()9 def __str__(self): # Return "title by author"10 return f"{self.title} by {self.author}"11 # Create a Book instance12b = Book("1984", "Orwell")# repr(b) calls __repr__: Book('1984', 'Orwell')13print(repr(b))# str(b) calls __str__: 1984 by Orwell14print(str(b))Output
Book('1984', 'Orwell')
1984 by OrwellPractice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
_× 12(× 9)× 9"× 8.× 6,× 4:× 4'× 4{× 4}× 4