__str__() and __repr__()
Methods that define an object’s text appearance: readable for the user (__str__) and technical for the programmer (__repr__).
- Returns
- Both methods must return a string (
str).
Example
#class Student:
def __init__(self, name, points):
self.name = name
self.points = points
def __str__(self):
return f"{self.name} ({self.points} pts)"
def __repr__(self):
return f"Student({self.name!r}, {self.points})"
emma = Student("Emma", 250)
print(emma)
print(f"Leader: {emma}")
print(repr(emma))
print([emma, Student("Jack", 90)])Definition and usage
#Without these methods, print(object) shows something like <__main__.Student object at 0x...>, which says very little. The __str__ method returns a readable description of the object meant for the user. It is used by print(), str(), and f-strings.
The __repr__ method returns a technical description, useful when debugging. A good representation looks like the code that creates the same object, e.g. Student("Emma", 250). It is used by the repr() function, the interactive console when you type a variable name, and printing a collection: a list of objects in print() shows the repr of each element.
If a class has only __repr__, Python also uses it in place of a missing __str__. So when you write only one of these methods, start with __repr__. In an f-string, you force the technical version with the !r suffix, e.g. f"{object!r}". Inside __repr__ itself, this suffix adds quotes around strings.
Syntax
#class Name:
def __str__(self):
return "description for the user"
def __repr__(self):
return "Name(...)"More examples
#class Course:
def __init__(self, title):
self.title = title
print(Course("Python"))The result looks something like <__main__.Course object at 0x104f3a2d0>. The memory address changes on every run.
class Badge:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Badge({self.name!r})"
badge = Badge("7-day streak")
print(badge)
print(str(badge) == repr(badge))
print(f"Earned: {badge!r}")Good practices
#- If you write only one of these methods, choose
__repr__. It also works as__str__, and it helps a lot when debugging. - In
__repr__, format strings with!rso the result includes quotes and looks like code:f"Student({self.name!r})". @dataclassgenerates__repr__automatically based on the class’s fields.
Related entries
#- str()Converts a value to a string.
- print()Writes values to standard output, which is the console by default.
- f-stringsStrings with inserted expression values: f"You have {points} pts".
- @dataclassA decorator that generates __init__, __repr__, and __eq__ for a data-storing class, based on type-annotated fields.
- Special methodsMethods with double underscores that let objects work with the ==, <, + and in operators, and with the len() function.
Spotted a mistake or missing an example? Write to us.