__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 representations
1class Book:
# The constructor takes a title and an author
2 def __init__(self, title, author):
# Store both values as instance attributes
3 self.title = title
4 self.author = author
5
# __repr__: an unambiguous form for developers, used by repr()
6 def __repr__(self):
# Return text that looks like the constructor call
7 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 instance
12b = Book("1984", "Orwell")
# repr(b) calls __repr__: Book('1984', 'Orwell')
13print(repr(b))
# str(b) calls __str__: 1984 by Orwell
14print(str(b))

Output

Book('1984', 'Orwell')
1984 by Orwell
Practice typing this code

Practice 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

More Python examples at level 4

← Python typing practice