Python 3D Academyবাংলা

__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: what print() and str() show to people
  • __repr__ is the record card: the exact, developer-friendly version, shown by repr() 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 by print() and str()
  • __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)])
{self.title!r} puts the title in with its quotes, the way repr() shows text. A list shows its items with __repr__.

Which one should I write? Step by step:

  1. If you write only one, write __repr__. Python uses it for print() too when there's no __str__.
  2. Make __repr__ look like the code that would make the object, like Book('Dune', 412).
  3. Add __str__ when people (not just developers) will read the output.
  4. 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 5 from __str__ gives TypeError: __str__ returned non-string (type int).
  • Printing instead of returning. A __str__ that prints and returns nothing gives the same TypeError: it returned None.
  • A list of objects uses repr. print([book]) shows each item's __repr__, not its __str__.
  • Calling the dunder yourself. Write str(book), not book.__str__().

Quiz

  1. What does this print?

    class Dog:
        def __init__(self, name):
            self.name = name
    
        def __str__(self):
            return "Dog called " + self.name
    
    print(Dog("Rex"))
  2. 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)])
  3. A class has __repr__ but no __str__. What does print(obj) use?

    • __repr__
    • Nothing: it's an error
    • The memory address
  4. 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))
  5. 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

  1. Give Book a __str__ that returns the title in double quotes, then "by" and the author, like "Dune" by Herbert.

  2. Give Point a __repr__ that returns text like Point(1, 2).

  3. Write a class Money(amount) whose __str__ gives text like 250 taka and whose __repr__ gives Money(250).