Special methods

Topic 2 of 4 in Classes and objects6 min readBeginnerFree course

Overview

Why does len("hello") work, and "a" + "b", and 3 < 5, and print([1, 2])? Because the built-in types define special methods — methods with double underscores on both sides, nicknamed dunder methods (“double underscore”). Define the same methods in your own classes, and your objects work with Python’s syntax too.

Special (dunder) methods hook into Python syntax. print(m) or str(m) calls str — readable text for users. m in the REPL, or repr(m), calls repr — precise text for developers. a == b calls eq — equality. a < b and sorted(items) call lt — ordering. len(m) calls len — size. a + b calls add — addition. x in m and for x in m call contains and iter — membership and iteration.

You never call these methods directly. You write len(playlist); Python calls playlist.__len__().

Text: str and repr

Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    def __str__(self):
        return f"({self.x}, {self.y})"

p = Point(3, 4)
print(p)          # (3, 4)        — uses __str__
p                 # Point(3, 4)   — the REPL uses __repr__
print([p])        # [Point(3, 4)] — containers use __repr__ for their items
f"{p!r}"          # 'Point(3, 4)'
  • __repr__ is for developers: unambiguous, ideally looking like the code that would recreate the object. It’s used in the REPL, in lists, in tracebacks and debuggers.
  • __str__ is for users: friendly and readable. print() and str() use it.

If you write only one, write __repr__ — Python falls back to it when there’s no __str__.

Comparison: eq and lt

By default, == on two of your objects checks whether they’re the same object, not whether they hold the same data:

Python
Point(3, 4) == Point(3, 4)     # False without __eq__

Define __eq__ to compare contents:

Python
def __eq__(self, other):
    if not isinstance(other, Point):
        return NotImplemented
    return (self.x, self.y) == (other.x, other.y)

Returning NotImplemented (a special built-in value, not an error) tells Python “I don’t know how to compare with that type” — Python then tries the other object’s method, or falls back to False for ==.

Comparing tuples of attributes is a neat trick: tuples compare item by item.

For ordering, define __lt__ (less than). That’s enough for sorted(), min(), max() and list.sort():

Python
def __lt__(self, other):
    return (self.x, self.y) < (other.x, other.y)

sorted([Point(2, 1), Point(1, 5)])    # [Point(1, 5), Point(2, 1)]

The other comparisons are __le__ (<=), __gt__ (>) and __ge__ (>=). The functools.total_ordering decorator fills them in from __eq__ and __lt__ — and Dataclasses can generate all of them.

Containers: len, contains, iter, getitem

Make a class behave like a collection:

Python
class Playlist:
    def __init__(self, name):
        self.name = name
        self.songs = []

    def add(self, song):
        self.songs.append(song)

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

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

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

    def __getitem__(self, index):
        return self.songs[index]

mix = Playlist("Road trip")
mix.add("Hey Jude")
mix.add("Imagine")
len(mix)                 # 2
"Imagine" in mix         # True
for song in mix:         # iteration works
    print(song)
mix[0]                   # 'Hey Jude'

With __len__, your object also becomes falsy when empty: if not mix: works.

Arithmetic: add and friends

Python
def __add__(self, other):
    return Point(self.x + other.x, self.y + other.y)

Point(1, 2) + Point(3, 4)        # Point(4, 6)

Others: __sub__ (-), __mul__ (*), __truediv__ (/). Return a new object rather than changing self — that’s what + means for numbers and strings. Only define operators where the meaning is obvious: adding two amounts of money makes sense; adding two users doesn’t.

Properties

Sometimes a value should look like an attribute but be calculated. The @property decorator turns a method into one:

Python
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @property
    def area(self):
        return self.width * self.height

r = Rectangle(3, 4)
r.area           # 12 — no brackets
r.width = 10
r.area           # 40 — always up to date
r.area = 5       # AttributeError: property 'area' of 'Rectangle' object has no setter

Properties are also used to validate changes: you can add a setter with @area.setter (or, more commonly, for something like @balance.setter) that checks the new value before storing it. Start with plain attributes; switch to a property later if you need logic — code using r.area won’t need to change.

A note on init

__init__ is itself a special method — it’s what makes Dog("Rex", 3) work. There are dozens more (__call__, __enter__/__exit__ for with, __hash__…); the Python docs’ “Data model” page lists them all.

Priorities for every class you write: a __repr__ always; __eq__ if objects can be compared; __lt__ if they can be sorted; container methods if it holds a collection — or let a dataclass write them for you.

Exercise

A Money class

Write a Money class storing an amount (in whole cents, an int) and a currency code. Add: __repr__ returning e.g. Money(1250, 'USD'); __str__ returning 12.50 USD; __eq__ (same amount and currency); __lt__ so lists of Money can be sorted; __add__ that adds two Money objects but raises ValueError if the currencies differ; and a read-only property dollars returning the amount as a float. Then print a Money object, its repr, the sum of two prices, a sorted list, an equality check, and catch the error from adding USD to EUR.

Python
class Money:
    def __init__(self, amount, currency):
        self.amount = amount          # whole cents
        self.currency = currency

    # __repr__, __str__, __eq__, __lt__, __add__, dollars property


a = Money(1250, "USD")
b = Money(399, "USD")
c = Money(500, "EUR")

Summary

  • Special (dunder) methods like __str__ let Python’s built-in syntax and functions work with your objects.
  • __str__ is for users (print, str); __repr__ is for developers (the REPL, lists, debugging) — always write __repr__.
  • __eq__ defines ==; __lt__ defines < and makes sorted() work; return NotImplemented for unsupported types.
  • __len__, __contains__, __iter__, __add__ and others make objects work with len, in, for and +.
  • @property turns a method into a read-only attribute that’s calculated when accessed.