Skip to content
Kuza Ndoto Academy

Dunder (Magic) Methods

Beginner → IntermediateChapter 8 · Page 46 of 564 min readUpdated 15 Nov 2026

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))
3 3 8 8

Printing objects: __str__ and __repr__

  • __str__ returns a friendly description for users. print() and str() 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)]))
KES 1,500 Money(1500, 'KES') KES 4,000 True True [Money(1500, 'KES'), Money(2500, 'KES')] KES 4,500

Some details worth noticing:

  • sorted() only needs __lt__ (less than) to order objects.
  • The list is printed with __repr__, while print(rent) uses __str__.
  • sum() starts with 0 + rent. Because int doesn't know how to add Money, Python tries rent.__radd__(0), the "reflected" (right-hand) version.
  • Returning NotImplemented tells Python "I don't know how to handle this type", so it can try the other object or raise a clear TypeError.
try:
    print(rent + 100)
except TypeError as error:
    print(error)
unsupported operand type(s) for +: 'Money' and 'int'

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", [])))
3 Amani Zuri ['Baraka', 'Zuri'] True False Present: Amani Present: Baraka Present: Zuri False

Slicing worked for free because __getitem__ passes the slice straight on to the underlying list.

Common dunder methods

MethodCalled 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)
Common mistake

__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).

Warning

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.

Tip

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 NotImplemented for types they don't support.
  • __len__, __getitem__, __contains__ and __iter__ make objects act like containers.
Up next · New chapter: Intermediate PythonIterators & GeneratorsProduce values one at a time.
→

Tip: use the ← and → keys to move between pages.