__str__ and __repr__: objects that print nicely
🌍 In real life. At a school event, you wear a name badge that says "Ana, Class 7": short and friendly, for people to read. The school office keeps a record card for you too: "Student(name='Ana', class=7, roll=12)". That one is exact, for the staff who need every detail.
Python objects can have both:
__str__is the badge: whatprint()andstr()show to people__repr__is the record card: the exact, developer-friendly version, shown byrepr()and when the object sits inside a list
The idea in one sentence: __str__ decides what print(obj) shows to people, and __repr__ gives an exact, code-like description for programmers.
Its words:
- dunder method: a method with two underscores on each side, which Python calls for you
__str__: the friendly text, used byprint()andstr()__repr__: the exact text, used in lists, the console and when there's no__str__
Why bother? Without them, print(book) shows something like <__main__.Book object at 0x7f3a9c2b1d90>: the class name and a memory address. It tells you nothing about the book, and the address changes every time you run the program.
Names like __str__ start and end with two underscores, so people call them dunder methods ("double underscore"). You don't call them yourself. Python calls them for you at the right moment, like __init__ when an object is made.
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"{self.title} ({self.pages} pages)"
def __repr__(self):
return f"Book({self.title!r}, {self.pages})"
b = Book("Dune", 412)
print(b) # the badge, for people
print(repr(b)) # the record card, for developers
print([b, Book("Emma", 474)])Which one should I write? Step by step:
- If you write only one, write
__repr__. Python uses it forprint()too when there's no__str__. - Make
__repr__look like the code that would make the object, likeBook('Dune', 412). - Add
__str__when people (not just developers) will read the output. - Both must return a string. Returning a number is a TypeError.
class Money:
def __init__(self, amount):
self.amount = amount
def __repr__(self):
return f"Money({self.amount})"
m = Money(250)
print(m) # no __str__, so print uses __repr__
print(str(m))Mistakes and edge cases.
- Returning something that isn't a string.
return 5from__str__givesTypeError: __str__ returned non-string (type int). - Printing instead of returning. A
__str__thatprints and returns nothing gives the same TypeError: it returnedNone. - A list of objects uses repr.
print([book])shows each item's__repr__, not its__str__. - Calling the dunder yourself. Write
str(book), notbook.__str__().
Quiz
What does this print?
class Dog: def __init__(self, name): self.name = name def __str__(self): return "Dog called " + self.name print(Dog("Rex"))What does this print?
class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point({self.x}, {self.y})" print([Point(1, 2), Point(3, 4)])A class has
__repr__but no__str__. What doesprint(obj)use?- __repr__
- Nothing: it's an error
- The memory address
What does this print?
class Temp: def __init__(self, c): self.c = c def __str__(self): return f"{self.c} C" def __repr__(self): return f"Temp({self.c})" t = Temp(21) print(t) print(repr(t))Which line has a mistake?
class Score: def __init__(self, points): self.points = points def __str__(self): return self.points print(Score(10))
Coding tasks
Give
Booka__str__that returns the title in double quotes, then "by" and the author, like"Dune" by Herbert.Give
Pointa__repr__that returns text likePoint(1, 2).Write a class
Money(amount)whose__str__gives text like250 takaand whose__repr__givesMoney(250).