Intermediate Python · Lesson 11 of 14

Special methods and dataclasses

Make your objects print nicely, compare, sort and add up with special methods like __str__, __eq__ and __lt__, then let dataclasses write them for you.

About 18 minutes · code runs in your browser, nothing to install

Python calls certain methods for you behind the scenes. They have double underscores on both sides, so people call them dunder (double underscore) or special methods. __init__ is one. Defining others lets your objects work with print(), ==, <, len(), + and more.

__str__ and __repr__

__str__ gives the friendly text that print() and str() show. __repr__ gives the exact, developer-facing text that repr() shows, and which Python also uses when the object sits inside a list. A good __repr__ looks like the code that would create the object.

Pythoneditable
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("Rain Over Lima", 320)
print(b)
print(repr(b))
print([b, Book("Small Hours", 180)])
Output
'Rain Over Lima' (320 pages)
Book('Rain Over Lima', 320)
[Book('Rain Over Lima', 320), Book('Small Hours', 180)]

!r inside an f-string uses repr(), which adds the quotes around the title.

Comparing, sizing and adding

__eq__ decides what == means. __lt__ (less than) is enough for sorted(), min() and max(). __len__ answers len() and __add__ answers +.

Pythoneditable
class Money:
    def __init__(self, amount, currency="EUR"):
        self.amount = amount
        self.currency = currency

    def __repr__(self):
        return f"Money({self.amount}, {self.currency!r})"

    def __eq__(self, other):
        return self.amount == other.amount and self.currency == other.currency

    def __lt__(self, other):
        return self.amount < other.amount

    def __add__(self, other):
        if self.currency != other.currency:
            raise ValueError("cannot add different currencies")
        return Money(self.amount + other.amount, self.currency)

print(Money(5) == Money(5), Money(5) == Money(7))
print(sorted([Money(20), Money(3), Money(12)]))
print(Money(5) + Money(2.5))
try:
    Money(5) + Money(5, "USD")
except ValueError as e:
    print("Error:", e)
Output
True False
[Money(3, 'EUR'), Money(12, 'EUR'), Money(20, 'EUR')]
Money(7.5, 'EUR')
Error: cannot add different currencies
Pythoneditable
class Playlist:
    def __init__(self, name, songs):
        self.name = name
        self.songs = list(songs)

    def __len__(self):
        return len(self.songs)

    def __contains__(self, song):
        return song in self.songs

    def __iter__(self):
        return iter(self.songs)

road = Playlist("Road trip", ["Blue Hills", "Fast Lane", "Home"])
print(len(road))
print("Home" in road)
for song in road:
    print("-", song)
Output
3
True
- Blue Hills
- Fast Lane
- Home

__contains__ answers the in operator and __iter__ makes the object usable in a for loop.

Dataclasses: less typing

Many classes just hold data. The @dataclass decorator from the dataclasses module reads the attributes you list (each with a type, explained in Type hints) and writes __init__, __repr__ and __eq__ for you.

Pythoneditable
from dataclasses import dataclass, field

@dataclass
class Product:
    name: str
    price: float
    tags: list = field(default_factory=list)
    qty: int = 0

tea = Product("Green tea", 4.5, ["drink"])
print(tea)
print(tea == Product("Green tea", 4.5, ["drink"]))
tea.qty += 10
print(tea.qty, Product("Mug", 7.0))
Output
Product(name='Green tea', price=4.5, tags=['drink'], qty=0)
True
10 Product(name='Mug', price=7.0, tags=[], qty=0)

field(default_factory=list) gives every product its own new list, avoiding the shared-default trap from the first lesson of this course.

Options change what is generated. order=True adds <, > and the rest, comparing the fields in order. frozen=True makes objects read-only, so they cannot be changed after creation and can be used as dictionary keys.

Pythoneditable
from dataclasses import dataclass, FrozenInstanceError

@dataclass(order=True, frozen=True)
class Version:
    major: int
    minor: int

releases = [Version(2, 1), Version(1, 9), Version(2, 0)]
print(sorted(releases))
print(max(releases))

v = Version(1, 0)
try:
    v.major = 5
except FrozenInstanceError:
    print("Error: a frozen dataclass cannot be changed")
Output
[Version(major=1, minor=9), Version(major=2, minor=0), Version(major=2, minor=1)]
Version(major=2, minor=1)
Error: a frozen dataclass cannot be changed

✎ Exercise

Write a dataclass Score with player: str and points: int, using order=True, but make it sort by points first: put points before player. Print the sorted list and the best score.

Hint: With order=True, objects are compared field by field in the order you wrote them, like tuples.

Your codewrite your answer, then Run
from dataclasses import dataclass

# your code here

scores = [Score(30, "Ana"), Score(45, "Ben"), Score(30, "Ada")]
print(sorted(scores))
print(max(scores).player)

Expected output:

[Score(points=30, player='Ada'), Score(points=30, player='Ana'), Score(points=45, player='Ben')]
Ben
Show a solution
Solutioneditable
from dataclasses import dataclass

@dataclass(order=True)
class Score:
    points: int
    player: str

scores = [Score(30, "Ana"), Score(45, "Ben"), Score(30, "Ada")]
print(sorted(scores))
print(max(scores).player)
Output
[Score(points=30, player='Ada'), Score(points=30, player='Ana'), Score(points=45, player='Ben')]
Ben

Check yourself

1. Which method does print(obj) use first?

2. Which method lets sorted() order your objects?

3. What does @dataclass write for you by default?

Spotted a mistake on this page? Tell us