Skip to content

Lesson 18 of 52Objects

Dunder Methods

Make your own classes print nicely, compare, sort, index, loop and add like built-in types.

16 min read0/5 questions

Why does len(my_list) work but my_list.length() does not? Why can you + two strings, in a dict, and loop over a file? Python's built-in behaviour is wired through special methods with double underscores, nicknamed dunder methods ("double underscore"). Learn a dozen of them and your own classes feel as natural as list and dict. Interviewers love asking about __eq__ and __hash__ in particular.

How the magic works

When you write len(x), Python calls type(x).__len__(x). When you write a + b, it calls a.__add__(b). When you print(x), it calls x.__str__(). These are ordinary methods; the only special thing is that the language calls them for you.

You writePython calls
repr(x), the REPL, inside listsx.__repr__()
str(x), print(x), f-stringsx.__str__() (falls back to __repr__)
a == ba.__eq__(b)
a < ba.__lt__(b)
len(x)x.__len__()
x[i]x.__getitem__(i)
for item in xx.__iter__()
item in xx.__contains__(item)
a + ba.__add__(b)
x(...)x.__call__(...)
Quick check
What does len(obj) actually do?
Need a nudge? A hint rules out a wrong answer.

__repr__ vs __str__

By default an object prints as something like <__main__.Point object at 0x10a3f>, which tells you nothing. Two methods fix that:

  • __repr__ is for developers: unambiguous, ideally valid Python that recreates the object. It is what you see in the REPL, in debuggers, in logs and inside containers like lists.
  • __str__ is for end users: readable. print and f-strings use it. If you skip it, Python uses __repr__.
Python
class Point: def __init__(self, x, y): self.x, self.y = x, y def __repr__(self): return f"Point({self.x!r}, {self.y!r})" def __str__(self): return f"({self.x}, {self.y})" p = Point(1, 2)print(p) # __str__print(repr(p)) # __repr__print([p, p]) # containers use __repr__ of their itemsprint(f"{p!r}") # !r forces repr inside an f-string
Output
Press Run (⌘ Enter) to see what happens.

If you only write one, write __repr__. It serves both purposes.

Predict the outputPython

What does this print?

class Tag:
  def __init__(self, name):
      self.name = name
  def __repr__(self):
      return f"Tag({self.name!r})"

print([Tag("a"), Tag("b")])
Need a nudge? Hints walk you through it.

Equality and hashing: a contract

By default a == b on your objects compares identity: two separate objects are never equal, even with the same data. Define __eq__ to compare by value.

There is a catch. Sets and dict keys use a hash, a number computed from the value, to find things fast. The rule is: objects that are equal must have equal hashes. So when you define __eq__, Python sets __hash__ to None and your objects become unhashable, unless you also define __hash__.

Python
class Money: def __init__(self, cents, currency): self.cents = cents self.currency = currency def __eq__(self, other): if not isinstance(other, Money): return NotImplemented return (self.cents, self.currency) == (other.cents, other.currency) def __hash__(self): return hash((self.cents, self.currency)) a = Money(500, "USD")b = Money(500, "USD")print(a == b, a is b)print(len({a, b})) # equal objects collapse into one set entryprint(a == 500) # NotImplemented lets Python answer False
Output
Press Run (⌘ Enter) to see what happens.

Return NotImplemented (a special constant, not an exception) when you do not know how to compare with the other type. Python then tries the other side and falls back to False for ==.

Only hash fields that never change. If an object's hash changes while it sits in a set, the set can no longer find it.

Quick check
You define __eq__ on a class but not __hash__. What happens when you do {obj}?
Need a nudge? A hint rules out a wrong answer.

Ordering and functools.total_ordering

To use <, sorted, min and max, define __lt__. Writing all six comparisons (<, <=, >, >=, ==, !=) by hand is tedious. The functools.total_ordering class decorator fills in the rest from __eq__ plus one of them.

Python
from functools import total_ordering @total_orderingclass 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 def __repr__(self): return "Version(" + ".".join(map(str, self.parts)) + ")" vs = [Version("1.10.0"), Version("1.2.3"), Version("1.9")]print(sorted(vs))print(Version("2.0") >= Version("1.99")) # generated by total_ordering
Output
Press Run (⌘ Enter) to see what happens.

Comparing tuples does the heavy lifting: Python compares tuples item by item, so (1, 10, 0) > (1, 9). Comparing the raw strings would put "1.10.0" before "1.9".

Containers: __len__, __getitem__, __iter__, __contains__

Implement these and your class works with len, indexing, slicing, for loops and in.

Python
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] # ints and slices both work def __iter__(self): return iter(self._songs) def __contains__(self, song): return song.lower() in (s.lower() for s in self._songs) p = Playlist("Intro", "Echoes", "Outro")print(len(p), p[0], p[-1], p[1:])for song in p: print("-", song)print("echoes" in p)
Output
Press Run (⌘ Enter) to see what happens.

Fun fact: with only __getitem__, Python can still loop over your object (it calls __getitem__(0), (1), ... until IndexError). Defining __iter__ is clearer and faster.

Match the pairs0/5 matched

Match the syntax to the dunder method it calls.

Choose an item, then its match on the other side.

Operators and callables

Operator overloading means defining what +, -, * and friends do for your type. a + b calls a.__add__(b). If that returns NotImplemented, Python tries b.__radd__(a) (the "reflected" version), which is how sum() (which starts from 0) can work with your objects.

__call__ makes an instance callable like a function. That is handy for objects that are "a function with memory".

Python
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 __mul__(self, k): return Vector(self.x * k, self.y * k) def __repr__(self): return f"Vector({self.x}, {self.y})" print(Vector(1, 2) + Vector(3, 4))print(Vector(1, 2) * 3) class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, value): return value * self.factor double = Multiplier(2)print(double(21), callable(double))
Output
Press Run (⌘ Enter) to see what happens.
How Python evaluates 3 * v
Pythonint 3Vector v3.__mul__(v)NotImplementedv.__rmul__(3)Vector(3, 6)

The left operand always gets the first try.

1/4
Predict the outputPython

What does this print?

class V:
  def __init__(self, n):
      self.n = n
  def __mul__(self, k):
      return V(self.n * k)

try:
  print((3 * V(2)).n)
except TypeError:
  print("TypeError")
Need a nudge? Hints walk you through it.

A preview: __enter__ and __exit__

The with statement is driven by two more dunders. __enter__ runs at the start of the block, __exit__ runs at the end, even if an exception happened. That is how with open(...) always closes the file. You will build your own in the context managers lesson.

class Timer:
    def __enter__(self): ...       # start the clock
    def __exit__(self, exc_type, exc, tb): ...   # stop it, even on error
ChallengeMedium

A Money value type

Write a class Money that stores an amount in whole cents (an int, to avoid float rounding) and a currency code.

  • Money(1050, "USD") has attributes cents and currency.
  • == compares by value: same cents and same currency. Comparing with a non-Money returns False.
  • Equal objects must have equal hashes, so Money can live in sets and be a dict key.
  • a + b returns a new Money. Adding different currencies raises ValueError.
  • sum(wallet) works on a list of Money (hint: sum starts from 0, so support 0 + money).
  • repr(m) is Money(1050, 'USD') and str(m) is 10.50 USD.
Money(250, "USD") + Money(100, "USD")   # Money(350, 'USD')
str(Money(5, "EUR"))                    # '0.05 EUR'
len({Money(1, "USD"), Money(1, "USD")}) # 1
Python
class Money: def __init__(self, cents: int, currency: str) -> None: pass # Add __eq__, __hash__, __add__, __radd__, __repr__ and __str__.
ChallengeEasy

A deck that behaves like a list

Write a class Deck that wraps a list of card names and supports Python's container syntax.

  • Deck(["AS", "10H", "3C"]) stores the cards in order.
  • len(deck) returns the number of cards.
  • deck[0] returns a card, and slices like deck[1:] return a list of cards.
  • for card in deck loops over the cards.
  • "as" in deck is case-insensitive (True here).
  • repr(deck) is Deck(3 cards).
d = Deck(["AS", "10H", "3C"])
len(d)        # 3
d[-1]         # "3C"
"10h" in d    # True
list(d)       # ["AS", "10H", "3C"]
Python
class Deck: def __init__(self, cards: list[str]) -> None: pass # Add __len__, __getitem__, __iter__, __contains__ and __repr__.
Key terms
dunder method
A method named __like_this__ that Python calls for built-in syntax such as len, + or in.
__repr__
The unambiguous developer representation, used by the REPL, logs and containers.
__eq__ / __hash__ contract
Equal objects must have equal hashes. Defining __eq__ alone makes a class unhashable.
NotImplemented
A constant a dunder returns to say "I cannot handle this type", letting Python try the other operand.
total_ordering
A functools decorator that derives all comparisons from __eq__ and one of __lt__, __le__, __gt__, __ge__.