ZetCode

Python magic methods

last modified November 29, 2026 Python 3.15

In this article we show how to use magic methods to make our classes work with Python's built-in functions and operators.

Magic methods, also called special methods or dunder methods (double underscore), are methods with names such as __str__ or __add__. We rarely call them directly. Python calls them for us: len(x) calls x.__len__(), a + b calls a.__add__(b), and print(x) calls x.__str__(). By defining these methods, a class takes part in the same protocols as the built-in types.

This article is an overview of the most common magic methods. Each method also has its own article in the Python dunder functions section.

The __str__ method

The __init__ method initializes a new object. The __str__ method returns a readable text form of the object; it is used by print, str, and f-strings.

person_str.py
class Person:

    def __init__(self, name, occupation):
        self.name = name
        self.occupation = occupation

    def __str__(self):
        return f'{self.name} is a {self.occupation}'


p = Person('John Doe', 'gardener')

print(p)
print(str(p))
print(f'Info: {p}')

Without __str__, the object would print as something like <__main__.Person object at 0x7f...>. All three ways of turning the object into text use our method.

$ python person_str.py
John Doe is a gardener
John Doe is a gardener
Info: John Doe is a gardener

The __repr__ method

The __repr__ method returns a representation meant for developers. It is used by repr, by the !r conversion in f-strings, by the interactive shell, and for the items of containers.

person_repr.py
class Person:

    def __init__(self, name, occupation):
        self.name = name
        self.occupation = occupation

    def __str__(self):
        return f'{self.name} is a {self.occupation}'

    def __repr__(self):
        return f'Person({self.name!r}, {self.occupation!r})'


p = Person('John Doe', 'gardener')

print(p)
print(repr(p))
print(f'{p!r}')

people = [p, Person('Roger Roe', 'driver')]
print(people)

A good __repr__ looks like the expression that creates the object. The !r conversion puts quotes around the strings. Note that printing a list shows the repr of its items, not their str. If a class defines only __repr__, it is also used in place of the missing __str__.

$ python person_repr.py
John Doe is a gardener
Person('John Doe', 'gardener')
Person('John Doe', 'gardener')
[Person('John Doe', 'gardener'), Person('Roger Roe', 'driver')]

Equality with __eq__

By default, == compares the identity of objects: two different objects are never equal, even if their attributes are the same. The __eq__ method defines value equality.

point_eq.py
class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

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


class Point2(Point):

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


print(Point(1, 2) == Point(1, 2))
print(Point2(1, 2) == Point2(1, 2))
print(Point2(1, 2) != Point2(3, 4))
print(Point2(1, 2) == (1, 2))
print(Point2(1, 2) in [Point2(0, 0), Point2(1, 2)])

When the other object is of an unknown type, __eq__ returns NotImplemented rather than False. Python then tries the reflected operation on the other operand and finally falls back to identity, so Point2(1, 2) == (1, 2) is False. We do not need to write __ne__; by default, != inverts the result of __eq__. The in operator on a list also uses __eq__.

$ python point_eq.py
False
True
True
False
True

Equality and hashing

Objects that are equal must have the same hash. That is why a class that defines __eq__ loses the inherited __hash__ method: Python sets it to None, and the objects can no longer be set elements or dictionary keys.

point_hash.py
class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

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

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


print(Point.__hash__)

try:
    visited = {Point(1, 2)}
except TypeError as e:
    print(e)


class HashablePoint(Point):

    def __hash__(self):
        return hash((self.x, self.y))


visited = {HashablePoint(1, 2), HashablePoint(1, 2), HashablePoint(0, 5)}
print(visited)
print(HashablePoint(0, 5) in visited)

The HashablePoint class adds a __hash__ method that hashes the same tuple that __eq__ compares. The set then treats the two Point(1, 2) objects as one element. Only objects that do not change after creation should be hashable; if a point moved while in a set, it would be lost in the wrong hash bucket.

$ python point_hash.py
None
cannot use 'Point' as a set element (unhashable type: 'Point')
{Point(1, 2), Point(0, 5)}
True

Ordering with total_ordering

The comparison operators <, <=, >, and >= call __lt__, __le__, __gt__, and __ge__. The functools.total_ordering decorator fills in the missing ones from __eq__ and one ordering method.

version_order.py
from functools import total_ordering


@total_ordering
class Version:

    def __init__(self, text):
        self.parts = tuple(int(p) for p in text.split('.'))

    def __repr__(self):
        return '.'.join(str(p) for p in self.parts)

    def __eq__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return self.parts == other.parts

    def __lt__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return self.parts < other.parts


versions = [Version(v) for v in ['3.10.2', '3.9.18', '3.15.0', '3.10.12']]

print(sorted(versions))
print(max(versions))
print(Version('3.10.2') >= Version('3.9.18'))
print('3.10.2' > '3.9.18')

Version numbers compare part by part as integers. The sorted and max functions need only __lt__; the >= operator comes from total_ordering. The last line shows why the class is useful: as strings, '3.10.2' is smaller than '3.9.18', because the character 1 is smaller than 9.

$ python version_order.py
[3.9.18, 3.10.2, 3.10.12, 3.15.0]
3.15.0
True
False

Arithmetic operators

Arithmetic operators map to methods such as __add__, __sub__, and __mul__. They should return a new object and leave the operands unchanged.

money_add.py
class Money:

    def __init__(self, cents):
        self.cents = cents

    def __repr__(self):
        return f'Money({self.cents / 100:.2f})'

    def __add__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return Money(self.cents + other.cents)

    def __mul__(self, n):
        if not isinstance(n, int):
            return NotImplemented
        return Money(self.cents * n)


price = Money(1250)
shipping = Money(399)

print(price + shipping)
print(price * 3)
print(price)

try:
    price + 5
except TypeError as e:
    print(e)

The Money class stores an amount in cents. Adding two amounts and multiplying by an integer produce new objects; the third line shows that price did not change. For an operand of another type, the methods return NotImplemented, and Python raises a TypeError with a clear message.

$ python money_add.py
Money(16.49)
Money(37.50)
Money(12.50)
unsupported operand type(s) for +: 'Money' and 'int'

Reflected operators

For 3 * price, Python first calls int.__mul__, which returns NotImplemented for a Money operand. It then tries the reflected method __rmul__ of the right operand.

money_radd.py
class Money:

    def __init__(self, cents):
        self.cents = cents

    def __repr__(self):
        return f'Money({self.cents / 100:.2f})'

    def __add__(self, other):
        if isinstance(other, Money):
            return Money(self.cents + other.cents)
        if other == 0:
            return self
        return NotImplemented

    __radd__ = __add__

    def __mul__(self, n):
        if not isinstance(n, int):
            return NotImplemented
        return Money(self.cents * n)

    __rmul__ = __mul__


items = [Money(1250), Money(399), Money(2000)]

print(3 * Money(1250))
print(sum(items))

Both operations are commutative, so the reflected methods are the same functions as the normal ones. The sum function starts with the integer 0 and computes 0 + items[0]; this calls Money.__radd__(items[0], 0). Accepting zero in the method lets us sum a list of amounts without passing a start value.

$ python money_radd.py
Money(37.50)
Money(36.49)

In-place operators

The augmented assignment a += b calls __iadd__ if the class defines it; otherwise it falls back to a = a + b. For mutable objects, __iadd__ usually changes the object in place and returns self.

basket_iadd.py
class Basket:

    def __init__(self, items=()):
        self.items = list(items)

    def __repr__(self):
        return f'Basket({self.items})'

    def __add__(self, other):
        return Basket(self.items + other.items)

    def __iadd__(self, other):
        self.items.extend(other.items)
        return self


a = Basket(['apple'])
alias = a

a = a + Basket(['pear'])
print(a, alias)

b = Basket(['apple'])
alias = b

b += Basket(['pear'])
print(b, alias, b is alias)

The + operator creates a new basket, so the alias still refers to the old one. The += operator extends the existing basket, which is seen through all its names. Built-in lists behave the same way.

$ python basket_iadd.py
Basket(['apple', 'pear']) Basket(['apple'])
Basket(['apple', 'pear']) Basket(['apple', 'pear']) True

The __len__ and __bool__ methods

The len function calls __len__. When an object is used in a boolean context, Python calls __bool__; if the class has no __bool__, it uses __len__ and treats zero length as false.

playlist_len.py
class Playlist:

    def __init__(self, name, songs=()):
        self.name = name
        self.songs = list(songs)

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


class Account:

    def __init__(self, balance):
        self.balance = balance

    def __bool__(self):
        return self.balance > 0


rock = Playlist('rock', ['Paranoid', 'Black Dog'])
jazz = Playlist('jazz')

print(len(rock), len(jazz))

for pl in [rock, jazz]:
    if pl:
        print(f'{pl.name}: {len(pl)} songs')
    else:
        print(f'{pl.name}: empty')

print(bool(Account(120)), bool(Account(0)))

The Playlist class has only __len__, so an empty playlist is false in the if statement. The Account class defines truthiness directly: an account is true when its balance is positive. Objects with neither method are always true.

$ python playlist_len.py
2 0
rock: 2 songs
jazz: empty
True False

Sequences with __getitem__

The __getitem__ method implements the indexing operator []. Together with __len__, it makes a class behave like a sequence.

deck.py
import random
from collections import namedtuple

Card = namedtuple('Card', ['rank', 'suit'])


class Deck:

    ranks = [str(n) for n in range(2, 11)] + list('JQKA')
    suits = '♠ ♥ ♦ ♣'.split()

    def __init__(self):
        self.cards = [Card(r, s) for s in self.suits for r in self.ranks]

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

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


deck = Deck()

print(len(deck))
print(deck[0], deck[-1])
print(deck[:3])
print(Card('Q', '♥') in deck)

for card in deck[12::13]:
    print(card.rank + card.suit, end=' ')
print()

random.seed(4)
print(random.choice(deck))

The deck passes the index to its internal list, so negative indexes and slices work as well. With only these two methods, the deck also supports in and for loops: without __contains__ and __iter__, Python calls __getitem__ with indexes 0, 1, 2, and so on until IndexError. The random.choice function needs just len and indexing.

$ python deck.py
52
Card(rank='2', suit='♠') Card(rank='A', suit='♣')
[Card(rank='2', suit='♠'), Card(rank='3', suit='♠'), Card(rank='4', suit='♠')]
True
A♠ A♥ A♦ A♣ 
Card(rank='4', suit='♥')

Mappings and containers

A dictionary-like class implements __getitem__, __setitem__, and __delitem__ for keys. The __contains__ method defines the in operator and __iter__ defines iteration.

inventory.py
class Inventory:

    def __init__(self):
        self.stock = {}

    def __setitem__(self, item, count):
        if count < 0:
            raise ValueError(f'negative count for {item}')
        self.stock[item] = count

    def __getitem__(self, item):
        return self.stock.get(item, 0)

    def __delitem__(self, item):
        del self.stock[item]

    def __contains__(self, item):
        return self.stock.get(item, 0) > 0

    def __iter__(self):
        return iter(sorted(self.stock))


inv = Inventory()
inv['pens'] = 12
inv['pads'] = 0
inv['ink'] = 3

print(inv['pens'], inv['erasers'])
print('pads' in inv, 'ink' in inv)

del inv['ink']
print(list(inv))

try:
    inv['cups'] = -1
except ValueError as e:
    print(e)

The Inventory class wraps a dictionary but changes its rules. Reading a missing item gives zero instead of a KeyError, the assignment rejects negative counts, and in is true only for items in stock. Iteration yields the item names in alphabetical order.

$ python inventory.py
12 0
False True
['pads', 'pens']
negative count for cups

Callable objects with __call__

The __call__ method makes instances callable like functions. Unlike a function, a callable object can keep state in its attributes.

counter_call.py
class Multiplier:

    def __init__(self, factor):
        self.factor = factor
        self.calls = 0

    def __call__(self, value):
        self.calls += 1
        return value * self.factor


double = Multiplier(2)

print(double(21))
print(list(map(double, [1, 2, 3])))
print(double.calls)
print(callable(double), callable(42))

The double object is called directly and passed to map like any function. It counts its calls in an attribute. The built-in callable function checks whether an object can be called. See Python callable objects for more examples.

$ python counter_call.py
42
[2, 4, 6]
4
True False

Custom formatting with __format__

The __format__ method receives the format specification that follows the colon in an f-string, or the second argument of format. A class can define its own specification language.

temperature.py
class Temperature:

    def __init__(self, celsius):
        self.celsius = celsius

    def __format__(self, spec):
        unit = 'C'
        if spec and spec[-1] in 'CFK':
            spec, unit = spec[:-1], spec[-1]

        if unit == 'F':
            value = self.celsius * 9 / 5 + 32
        elif unit == 'K':
            value = self.celsius + 273.15
        else:
            value = self.celsius

        return format(value, spec or '.1f') + ' ' + unit


t = Temperature(21.5)

print(f'{t}')
print(f'{t:F}')
print(f'{t:.0fF}')
print(f'[{t:>8.2fK}]')
print(format(t, 'C'), '{:F}'.format(t))

Our specification is a normal float specification followed by an optional unit letter. The method removes the unit, converts the temperature, and passes the rest to the built-in format function for the number. An empty specification gives one decimal place in Celsius.

$ python temperature.py
21.5 C
70.7 F
71 F
[  294.65 K]
21.5 C 70.7 F

Conversion methods

The int and float functions call __int__ and __float__. The __index__ method is stricter: it says that the object is an integer by nature. It is used for indexing and slicing and by hex, bin, oct, and range.

conversions.py
class Char:

    def __init__(self, value):
        self.value = value

    def __int__(self):
        return ord(self.value)

    def __float__(self):
        return float(ord(self.value))

    def __index__(self):
        return ord(self.value)


c = Char('a')

print(int(c), float(c))
print(hex(c), bin(c), oct(c))

colors = ['red'] * 100
print(colors[Char('b')])
print(range(Char('a'), Char('e'))[-1])

A Char object converts to the code point of its character. Since it has __index__, it can be used directly as a list index and as a range bound. A float, for example, has __int__ but no __index__, so colors[1.0] is an error.

$ python conversions.py
97 97.0
0x61 0b1100001 0o141
red
100

Two-dimensional vector

In the last example we put several methods together in a vector class. It supports addition, subtraction, negation, scaling, the dot product, the length, equality, and unpacking.

vector.py
import math


class Vec2D:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f'Vec2D({self.x}, {self.y})'

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

    def __add__(self, other):
        if not isinstance(other, Vec2D):
            return NotImplemented
        return Vec2D(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return self + -other

    def __neg__(self):
        return Vec2D(-self.x, -self.y)

    def __mul__(self, k):
        if not isinstance(k, (int, float)):
            return NotImplemented
        return Vec2D(self.x * k, self.y * k)

    __rmul__ = __mul__

    def __matmul__(self, other):
        return self.x * other.x + self.y * other.y

    def __abs__(self):
        return math.hypot(self.x, self.y)

    def __iter__(self):
        return iter((self.x, self.y))


u = Vec2D(3, 4)
v = Vec2D(1, -2)

print(u + v, u - v, -v)
print(2 * u, u * 0.5)
print(u @ v, abs(u))
print(u == Vec2D(3, 4), u != v)

x, y = u
print(x, y, tuple(v))

The __sub__ method reuses __add__ and __neg__. Scaling works from both sides thanks to __rmul__. The @ operator, which calls __matmul__, computes the dot product, and abs calls __abs__. The __iter__ method returns an iterator over the coordinates, which makes tuple unpacking and tuple(v) work.

$ python vector.py
Vec2D(4, 2) Vec2D(2, 6) Vec2D(-1, 2)
Vec2D(6, 8) Vec2D(1.5, 2.0)
-5 5.0
True True
3 4 (1, -2)

Source

Special method names – Python language reference

functools.total_ordering – Python documentation

In this article we have used magic methods to give custom classes a string representation, equality, hashing, ordering, arithmetic operators, container behavior, and custom formatting. See also Python __repr__, Python __eq__, Python __getitem__, Python object creation, and Python context managers.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.