Special methods
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.
You never call these methods directly. You write len(playlist); Python calls playlist.__len__().
Text: str and repr
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()andstr()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:
Point(3, 4) == Point(3, 4) # False without __eq__Define __eq__ to compare contents:
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():
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:
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
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:
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 setterProperties 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.
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.
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")class Money:
def __init__(self, amount, currency):
self.amount = amount # whole cents
self.currency = currency
def __repr__(self):
return f"Money({self.amount}, {self.currency!r})"
def __str__(self):
return f"{self.amount / 100:.2f} {self.currency}"
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return (self.amount, self.currency) == (other.amount, other.currency)
def __lt__(self, other):
if self.currency != other.currency:
raise ValueError("can't compare different currencies")
return self.amount < other.amount
def __add__(self, other):
if self.currency != other.currency:
raise ValueError(f"can't add {other.currency} to {self.currency}")
return Money(self.amount + other.amount, self.currency)
@property
def dollars(self):
return self.amount / 100
a = Money(1250, "USD")
b = Money(399, "USD")
c = Money(500, "EUR")
print(a) # 12.50 USD
print(repr(a)) # Money(1250, 'USD')
print(a + b) # 16.49 USD
print(sorted([a, b, Money(5, "USD")])) # [Money(5, 'USD'), Money(399, 'USD'), Money(1250, 'USD')]
print(a == Money(1250, "USD"), a == b) # True False
print(b.dollars) # 3.99
try:
a + c
except ValueError as error:
print("Error:", error) # Error: can't add EUR to USDSummary
- 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 makessorted()work; returnNotImplementedfor unsupported types.__len__,__contains__,__iter__,__add__and others make objects work withlen,in,forand+.@propertyturns a method into a read-only attribute that’s calculated when accessed.