Reading history

Python Magic (Dunder) Methods with Examples

5 min read 2 views

Learn Python magic methods: __str__ and __repr__, __add__ and __rmul__, __eq__, __lt__ and __hash__, __len__, __getitem__, __contains__, __iter__ and __call__.

Why does len(my_list) work, or a + b for numbers and strings, or for x in data? Behind each of these, Python calls a special method whose name starts and ends with two underscores, such as __len__, __add__ and __iter__. These are called magic methods or dunder methods (“double underscore”). By defining them in your own classes, your objects can be printed nicely, compared, added, sorted, indexed and looped over just like built-in types.

In this lesson you will learn

  • __str__ and __repr__ for printing
  • Arithmetic with __add__, __mul__ and __rmul__
  • Comparison with __eq__ and __lt__, and why __hash__ matters
  • Container behaviour: __len__, __getitem__, __contains__, __iter__
  • Callable objects with __call__

You should know classes and objects.

A Money Class: Printing, Maths and Comparison

class Money:
    def __init__(self, taka, paisa=0):
        total = taka * 100 + paisa
        self.paisa = total                       # store everything in paisa

    def __repr__(self):                          # for developers: unambiguous
        return f"Money({self.paisa // 100}, {self.paisa % 100})"

    def __str__(self):                           # for users: readable
        return f"৳{self.paisa // 100}.{self.paisa % 100:02d}"

    def __add__(self, other):                    # m1 + m2
        return Money(0, self.paisa + other.paisa)

    def __mul__(self, n):                        # m * 3
        return Money(0, self.paisa * n)

    __rmul__ = __mul__                           # 3 * m

    def __eq__(self, other):                     # m1 == m2
        return isinstance(other, Money) and self.paisa == other.paisa

    def __lt__(self, other):                     # m1 < m2 (lets sorted() work)
        return self.paisa < other.paisa

    def __hash__(self):                          # needed again after defining __eq__
        return hash(self.paisa)

    def __bool__(self):                          # if m: ...
        return self.paisa != 0


tea = Money(15)
snack = Money(32, 50)
print(tea, snack, repr(snack))
print(tea + snack, 3 * tea, tea * 2)
print(Money(15) == tea, tea < snack, sorted([snack, tea, Money(5)]))
print(bool(Money(0)), len({Money(15), tea}))

Output

৳15.00 ৳32.50 Money(32, 50)
৳47.50 ৳45.00 ৳30.00
True True [Money(5, 0), Money(15, 0), Money(32, 50)]
False 1
  • The amount is stored in whole paisa, which avoids floating-point rounding errors with money.
  • __str__ is used by print() and str() and should be friendly for users. __repr__ is used by repr(), the interactive shell and inside lists, and should be unambiguous for developers. The sorted list shows repr values.
  • __add__ runs for tea + snack and __mul__ for tea * 2. Python tries int.__mul__ first for 3 * tea; when that fails, it calls tea.__rmul__(3), so both orders work.
  • __eq__ defines ==. Without it, two equal amounts would be different objects and compare as false.
  • __lt__ defines <, which is all sorted() needs. functools.total_ordering can fill in <=, > and >= from it.
  • Defining __eq__ removes the default __hash__, so __hash__ is added back to allow use in sets and as dictionary keys. Equal amounts hash the same, so the set holds one item.
  • __bool__ decides truthiness, so if amount: is false for zero.

A Playlist Class: Acting Like a Container

class Playlist:
    def __init__(self, name, songs=None):
        self.name = name
        self.songs = list(songs or [])

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

    def __getitem__(self, index):          # p[0], p[-1], p[1:3] and for-loops
        if isinstance(index, slice):
            return Playlist(self.name + " (part)", self.songs[index])
        return self.songs[index]

    def __contains__(self, song):          # "x" in p
        return song.lower() in (s.lower() for s in self.songs)

    def __iter__(self):                    # for song in p
        return iter(self.songs)

    def __call__(self, n):                 # p(2): the object acts like a function
        return f"Now playing: {self.songs[n]}"

    def __repr__(self):
        return f"Playlist({self.name!r}, {len(self)} songs)"


p = Playlist("Monsoon", ["Song A", "Song B", "Song C", "Song D"])
print(len(p), p[0], p[-1])
print(p[1:3], p[1:3].songs)
print("song b" in p, "Song Z" in p)
print([s.upper() for s in p])
print(p(2))
print(repr(p))

Output

4 Song A Song D
Playlist('Monsoon (part)', 2 songs) ['Song B', 'Song C']
True False
['SONG A', 'SONG B', 'SONG C', 'SONG D']
Now playing: Song C
Playlist('Monsoon', 4 songs)
  • __len__ makes len(p) work.
  • __getitem__ handles p[0] and p[-1]. When the index is a slice, it returns a new Playlist, just as slicing a list returns a list.
  • __contains__ controls the in operator; here it ignores capital letters.
  • __iter__ returns an iterator, so the object works in for loops and comprehensions.
  • __call__ lets an object be called like a function: p(2).
  • {self.name!r} in __repr__ shows the name with quotes, making clear it is a string.

Common Magic Methods

MethodCalled by
__init__Creating an object: Money(15)
__str__, __repr__print(x), repr(x)
__eq__, __lt__, __le__, __gt__==, <, <=, >
__add__, __sub__, __mul__, __truediv__+, -, *, /
__len__, __getitem__, __setitem__len(x), x[i], x[i] = v
__contains__, __iter__in, for loops
__bool__, __hash__if x:, sets and dictionary keys
__call__x()
__enter__, __exit__with statements

Common Mistakes

  1. Calling magic methods directly, such as p.__len__(). Use len(p); the built-in may do extra checks.
  2. Defining __eq__ without __hash__, then being surprised the objects cannot go in a set.
  3. Returning a string from __len__ or anything other than a non-negative integer.
  4. Making + do something surprising. Operators should behave the way readers expect.

Practice Exercises

Exercise 1. Add a __sub__ method to Money so Money(50) - Money(12, 50) prints ৳37.50.

Show answer
def __sub__(self, other):
    return Money(0, self.paisa - other.paisa)

Exercise 2. Write a Vector class with x and y where Vector(1, 2) + Vector(3, 4) gives Vector(4, 6) and abs(Vector(3, 4)) gives 5.0.

Show answer
import math

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

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

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

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

print(Vector(1, 2) + Vector(3, 4), abs(Vector(3, 4)))

Frequently Asked Questions

What if I define only __repr__ and not __str__?

Then print() and str() fall back to __repr__. Defining __repr__ is the more important of the two.

Do dataclasses write these methods for me?

Yes. A dataclass generates __init__, __repr__ and __eq__, and with order=True it also adds comparison methods.

Summary

  • Magic methods connect your class to Python’s built-in syntax.
  • __repr__ and __str__ control printing.
  • Operators, comparisons, len, indexing, in and loops all map to dunder methods.
  • When you define __eq__, also define __hash__ if the objects should go in sets.

Next: Python Logging.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *