Skip to contentSkip to navigation

Module 15 · Lesson 01

Special (Dunder) Methods

Make your classes behave like built-in types: __repr__ and __str__ for printing, __eq__ and ordering for comparing, __add__ and friends for arithmetic, and __len__, __getitem__, __contains__ and __iter__ for containers.

  • About 9 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Print with repr and str
  • Compare and sort your objects
  • Add objects with +
  • Watch + become a method call

Teach your class Python's moves

Methods with double underscores let your objects work with print, ==, +, len and for loops.

  • Printing

    __repr__ for the shell and debugging, __str__ for print().

  • Comparing

    __eq__ runs for ==, __lt__ for < and for sorted().

  • Arithmetic

    __add__ runs for +, __mul__ for *, and so on.

  • Containers

    __len__, __getitem__, __contains__ and __iter__ make it act like a list.

Dunders everywhere

Every built-in type is built from these same methods.

  • MoneyA Money class can add amounts with + and refuse to add pounds to euros.
  • Game movementpos + velocity moves a sprite when the Vector class has __add__.
  • Playlistslen(playlist) and for song in playlist need just two small methods.
  • Datesdate2 - date1 gives a time gap, because dates define __sub__.

Three calls in disguise

This line looks like plain Python, but each part calls one of the box's own methods. Tap each part to see which.

Part 1 of 3

Tap any part of the code below, or press Next.1 of 3 explored

__len__:len(box) calls box.__len__().

Make objects act built in

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6repr and str

print() and f-strings use __str__. A list of objects uses __repr__.

Your turn: Delete __str__. Which of the three lines change?

Python
class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

    def __repr__(self):
        return f"Book({self.title!r}, {self.pages})"

    def __str__(self):
        return f"{self.title}, {self.pages} pages"

b = Book("Dune", 412)
print(b)
print([b])
print(f"Reading {b}")
Output
Press Run to see what it prints.

Watch + become a method call

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. class Coins:
  2. def __init__(self, n):
  3. self.n = n
  4. def __add__(self, other):
  5. return Coins(self.n + other.n)
  6. def __repr__(self):
  7. return f"Coins({self.n})"
  8. a = Coins(3)
  9. b = Coins(4)
  10. total = a + b
  11. print(total)
  12. print(a)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Which one does an f-string use?

class T:
    def __repr__(self):
        return "R"
    def __str__(self):
        return "S"
x = T()
print(f"{x}", repr(x))

0 of 6 answered

Common dunder misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Operators are method calls

Special methods have names that start and end with two underscores, so Python programmers call them dunder ("double underscore") methods. You have already written one: __init__. You almost never call them yourself. Python calls them when you use an operator or a built-in function:

You write Python calls
repr(x), the shell x.__repr__()
str(x), print(x), f-strings x.__str__()
x == y x.__eq__(y)
x < y x.__lt__(y)
x + y x.__add__(y)
len(x) x.__len__()
x[i] x.__getitem__(i)
item in x x.__contains__(item)
for v in x x.__iter__()
if x: x.__bool__()

So 3 + 4 is really (3).__add__(4). Defining these methods in your class gives your objects the same abilities.

Printing: repr and str

Try it 1: edit me, then Run
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(2, 5)
print(p)          # (2, 5)        uses __str__
print([p])        # [Point(2, 5)] containers use __repr__
print(repr(p))    # Point(2, 5)
Output
Press Run to see what it prints.
  • __repr__ is for developers. It should be unambiguous, ideally looking like the code that would recreate the object. Lists, dictionaries, the interactive shell and debuggers show it.
  • __str__ is for users: a friendly, readable form used by print and f-strings.

If you only write one, write __repr__: when __str__ is missing, Python falls back to __repr__. Both must return a string; printing inside them is a mistake.

Equality and hashing

By default, == between two of your objects is True only if they are the very same object. Define __eq__ to compare by value:

Try it 2: edit me, then Run
    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)
Output
Press Run to see what it prints.

Returning the special value NotImplemented (not raising it) tells Python "I do not know how to compare with that type", so Python can try the other object's method and finally fall back to False.

Defining __eq__ has a side effect: Python sets __hash__ to None, so the objects can no longer be put in a set or used as dictionary keys. That is deliberate, because equal objects must have equal hashes. If your objects never change after creation, add __hash__ returning hash((self.x, self.y)), hashing exactly the fields __eq__ compares.

Ordering

<, <=, > and >= call __lt__, __le__, __gt__ and __ge__. Defining __lt__ alone is enough for sorted(), min() and max(). To get all four comparisons from two methods, decorate the class with functools.total_ordering and define __eq__ plus __lt__:

Try it 3: edit me, then Run
from functools import total_ordering

@total_ordering
class Version:
    def __init__(self, text):
        self.parts = tuple(int(p) for p in text.split("."))
    def __eq__(self, other):
        return self.parts == other.parts
    def __lt__(self, other):
        return self.parts < other.parts
Output
Press Run to see what it prints.

Comparing tuples of numbers means Version("1.10") > Version("1.9"), which comparing the strings would get wrong.

Arithmetic

+, -, * and / call __add__, __sub__, __mul__ and __truediv__. They should return a new object and leave both operands unchanged:

Try it 4: edit me, then Run
    def __add__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return Point(self.x + other.x, self.y + other.y)
Output
Press Run to see what it prints.

When the left operand does not know how to handle the right one, Python tries the right operand's reflected method, such as __radd__ or __rmul__. That matters for sum(), which starts from the integer 0: 0 + money fails unless Money defines __radd__ to accept 0. Reflected methods also allow 3 * vector as well as vector * 3.

Container behaviour

A class that holds items can act like a list:

Try it 5: edit me, then Run
class Playlist:
    def __init__(self, songs):
        self.songs = list(songs)
    def __len__(self):
        return len(self.songs)
    def __getitem__(self, index):
        return self.songs[index]
    def __contains__(self, song):
        return song in self.songs
    def __iter__(self):
        return iter(self.songs)
Output
Press Run to see what it prints.

Now len(p), p[0], p[-1], p[1:3] (the slice object is passed straight to the list), "intro" in p and for song in p all work. If __bool__ is missing, Python uses __len__ for truth: an empty playlist is falsy, just like an empty list.

Use them with restraint

Special methods should do what a reader expects. + on money should add amounts, not send an email. If an operation has no obvious meaning for your class, give it an ordinary, well-named method instead. A small, predictable set of dunder methods, usually __repr__, __eq__ and whatever protocol the class genuinely supports, makes a class pleasant to use. The dataclasses module, which can write __init__, __repr__ and __eq__ for you, builds on exactly these methods.

Syntax

The general shape of the statements in this lesson.

syntax.py
class Thing:
    def __repr__(self): return "Thing(...)"   # repr(), lists, shell
    def __str__(self):  return "friendly"     # print(), str(), f-strings
    def __eq__(self, other):                  # ==
        if not isinstance(other, Thing):
            return NotImplemented
        return self.key == other.key
    def __hash__(self): return hash(self.key) # needed with __eq__ for sets
    def __lt__(self, other): ...              # <, sorted(), min(), max()
    def __add__(self, other): ...             # self + other
    def __radd__(self, other): ...            # other + self, sum()
    def __mul__(self, n): ...                 # self * n
    def __len__(self): ...                    # len()
    def __getitem__(self, i): ...             # self[i], slices
    def __contains__(self, item): ...         # item in self
    def __iter__(self): ...                   # for x in self
    def __bool__(self): ...                   # if self:

@functools.total_ordering   # __eq__ + __lt__ give <= > >=
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A Money type that adds and sums

Beginner

Store amounts of money as whole cents to avoid floating-point errors. Make Money print nicely, compare by value, add to other Money, and work with sum() over a list of prices.

Python
class Money:
    def __init__(self, cents):
        self.cents = cents

    def __repr__(self):
        return f"Money({self.cents})"

    def __str__(self):
        return f"${self.cents // 100}.{self.cents % 100:02}"

    def __eq__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return self.cents == other.cents

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

    def __radd__(self, other):
        if other == 0:
            return self
        return NotImplemented

coffee = Money(350)
cake = Money(425)
print(coffee + cake)
print([coffee, cake])
print(coffee == Money(350), coffee == 350)
print("Total:", sum([coffee, cake, Money(5)]))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

print uses __str__, while the list shows each item's __repr__. Comparing with a plain number returns NotImplemented, so Python falls back to False instead of crashing. sum begins with 0 + coffee; int cannot add Money, so Python calls coffee.__radd__(0), which returns the money unchanged, and the rest of the sum uses __add__.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Defining __eq__ and then using a set

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
class Tag:
    def __init__(self, name):
        self.name = name
    def __eq__(self, other):
        return self.name == other.name

print(len({Tag('a'), Tag('a')}))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

TypeError: unhashable type: 'Tag'

Write this instead

class Tag:
    def __init__(self, name):
        self.name = name
    def __eq__(self, other):
        return self.name == other.name
    def __hash__(self):
        return hash(self.name)

print(len({Tag('a'), Tag('a')}))

Why it happens

Defining __eq__ removes the default __hash__, because equal objects must hash the same.

In the real world

Where this shows up in software people use every day.

  1. Sorting software versions correctly

    Developer tools

    A package manager must decide which release of a library is newest. Sorting version strings as text puts 1.10.0 before 1.9.2, which is wrong. A small Version class compares the numeric parts instead, and total_ordering fills in every comparison operator.

    Why Python fits

    Tuples compare item by item, so (1, 10, 0) is greater than (1, 9, 2), while the strings compare character by character. sorted and max only need __lt__; >= comes from total_ordering. Adding __hash__ on the same tuple keeps versions usable in a set, so the duplicate release is counted once.

    Python
    from functools import total_ordering
    
    @total_ordering
    class Version:
        def __init__(self, text):
            self.text = text
            self.parts = tuple(int(part) for part in text.split("."))
    
        def __repr__(self):
            return f"Version({self.text!r})"
    
        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
    
        def __hash__(self):
            return hash(self.parts)
    
    releases = ["1.9.2", "1.10.0", "1.2.11", "2.0.0", "1.10.0"]
    print("As text:", sorted(releases))
    versions = sorted(Version(r) for r in releases)
    print("As versions:", versions)
    print("Newest:", max(versions).text)
    print("1.10.0 >= 1.9.2:", Version("1.10.0") >= Version("1.9.2"))
    print("Unique:", len(set(versions)))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Should I ever call a dunder method directly?

Rarely. Write len(x) rather than x.__len__(), and a + b rather than a.__add__(b). The built-ins also handle fallbacks such as reflected methods, which direct calls skip.

What is the difference between returning NotImplemented and raising NotImplementedError?

NotImplemented is a value returned from operator methods to let Python try something else. NotImplementedError is an exception for methods a subclass is supposed to provide. They are not interchangeable.

Do I need __iter__ if I already have __getitem__?

A for loop can fall back to calling __getitem__ with 0, 1, 2 and so on until IndexError, but defining __iter__ is clearer and faster, and works for containers that are not indexed by position.

Can dataclasses write these methods for me?

Yes. @dataclass generates __init__, __repr__ and __eq__; order=True adds comparisons and frozen=True makes instances immutable and hashable. Knowing the methods underneath helps when you need to customise them.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 18 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.