Dunder (Magic) Methods
Dunder methods (short for "double underscore", also called magic or special methods) have names like __str__ and __add__. Python calls them behind the scenes, and defining them lets your own objects work with print(), +, ==, len(), loops and more.
How they work
When you write len(x), Python actually calls x.__len__(). When you write a + b, it calls a.__add__(b). Built-in types such as lists and strings already define these methods, which is why they work with the built-in functions and operators. You almost never call dunder methods directly; you define them and let Python call them.
print(len([1, 2, 3]), [1, 2, 3].__len__()) print(5 + 3, (5).__add__(3))
Printing objects: __str__ and __repr__
__str__returns a friendly description for users.print()andstr()use it.__repr__returns an unambiguous description for developers, ideally looking like code that recreates the object. The interactive shell,repr(), and lists of objects use it.
If you define only one, define __repr__: Python falls back to it when there's no __str__.
A complete example: a Money class
class Money:
def __init__(self, amount, currency="KES"):
self.amount = amount
self.currency = currency
def __repr__(self):
return f"Money({self.amount}, {self.currency!r})"
def __str__(self):
return f"{self.currency} {self.amount:,}"
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
if other.currency != self.currency:
raise ValueError("Cannot add different currencies")
return Money(self.amount + other.amount, self.currency)
def __radd__(self, other):
if other == 0: # lets sum() start from 0
return self
return self.__add__(other)
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return (self.amount, self.currency) == (other.amount, other.currency)
def __lt__(self, other):
return self.amount < other.amount
rent = Money(1500)
fees = Money(2500)
print(rent)
print(repr(rent))
print(rent + fees)
print(rent == Money(1500), rent < fees)
print(sorted([fees, rent]))
print(sum([rent, fees, Money(500)]))
Some details worth noticing:
sorted()only needs__lt__(less than) to order objects.- The list is printed with
__repr__, whileprint(rent)uses__str__. sum()starts with0 + rent. Becauseintdoesn't know how to addMoney, Python triesrent.__radd__(0), the "reflected" (right-hand) version.- Returning
NotImplementedtells Python "I don't know how to handle this type", so it can try the other object or raise a clearTypeError.
try:
print(rent + 100)
except TypeError as error:
print(error)
Container-like objects
Define __len__, __getitem__, __contains__ and __iter__ to make an object behave like a list.
class ClassRegister:
def __init__(self, form, students):
self.form = form
self.students = list(students)
def __len__(self):
return len(self.students)
def __getitem__(self, index):
return self.students[index]
def __contains__(self, name):
return name in self.students
def __iter__(self):
return iter(self.students)
def __bool__(self):
return len(self.students) > 0
register = ClassRegister("4 East", ["Amani", "Baraka", "Zuri"])
print(len(register))
print(register[0], register[-1])
print(register[1:])
print("Zuri" in register, "Juma" in register)
for name in register:
print("Present:", name)
print(bool(ClassRegister("1 West", [])))
Slicing worked for free because __getitem__ passes the slice straight on to the underlying list.
Common dunder methods
| Method | Called by |
|---|---|
__init__(self, ...) | Creating an object: Money(5) |
__str__(self) / __repr__(self) | print(x), str(x) / repr(x) |
__len__(self) | len(x) |
__getitem__(self, key) | x[key] |
__setitem__(self, key, value) | x[key] = value |
__contains__(self, item) | item in x |
__iter__(self) | for item in x |
__eq__, __lt__, __le__, __gt__ | ==, <, <=, > |
__add__, __sub__, __mul__ | +, -, * |
__bool__(self) | if x:, bool(x) |
__call__(self, ...) | Calling the object like a function: x() |
__enter__ / __exit__ | The with statement (see Context Managers) |
__str__ and __repr__ must return a string, not print one. If __str__ prints and returns nothing, print(obj) fails with TypeError: __str__ returned non-string (type NoneType).
When you define __eq__, Python makes your objects unhashable, so they can no longer be dictionary keys or set members (TypeError: unhashable type: 'Money'). If you need that, also define __hash__, for example return hash((self.amount, self.currency)), and treat the objects as unchangeable.
Don't invent your own __names__. Names with double underscores on both sides are reserved for Python. Use them only to implement the special methods Python already defines.
Key points
- Dunder methods let your objects work with built-in functions and operators.
- Define
__repr__(for developers) and__str__(for users) to control printing. - Operator methods should return
NotImplementedfor types they don't support. __len__,__getitem__,__contains__and__iter__make objects act like containers.
Tip: use the ← and → keys to move between pages.
