Dunder methods are specially named methods, such as __len__, that connect a type to Python’s built-in operations and protocols.
Define readable representations, equality and supported operations while handling incompatible operand types correctly.
Your classes now have named operations. Python's built-ins and operators also have
contracts a class can implement: how to represent an instance, compare it, measure
it, or add it to another. Dunder means double underscore, as in __repr__.
Follow which operation requests which method, including what happens when the
other operand is a type your class does not support.

Make it readable: __repr__
Your account works. Now try to look at one.
The default representation identifies the type and an object-specific identity
marker, but not the account's fields. print requests the object's string form.
Our class inherits the default __str__, which falls back to __repr__; defining
__repr__ therefore improves this output too:
The !r inside the f-string formats the owner's representation, including quotes
and escaping. This works even when a name contains an apostrophe. An informative
representation often resembles a constructor call, but not every object can or
should be recreated from its representation. Avoid exposing credentials or other
sensitive state in it.
The list in the second print uses each element's representation. That is different
from printing an element directly when the type also supplies __str__. The
illustration groups these hooks together; their exact request paths are:
| Expression | What this ordinary user-defined type supplies |
|---|---|
repr(a) |
__repr__, returning a diagnostic string. |
str(a) or print(a) |
__str__; the inherited default falls back to __repr__. |
print([a]) |
The list representation uses repr for its elements. |
Add __str__ returning f"{self.owner}: {self.balance}" to the example, then print
the account alone, repr(account), and [account]. Only the first should use the
new user-facing form. This is useful when a receipt and a debugging display need
different amounts of detail.
It must return a string, not print one:
TypeErrorRun it and read the error. Then make it print Account(Ada) exactly once.
Preparing this topic’s interactive investigation…
Say what equal means: __eq__
For a plain user-defined class inheriting the default comparison, distinct instances compare unequal even when their attributes match:
class Money:
def __init__(self, amount):
self.amount = amount
print(Money(5) == Money(5))Define what equality means for your type and it behaves the way people expect:
An unsupported operand is not the same as an unequal one
The first two comparisons return True and False by comparing amounts. For the
third, Money.__eq__ returns the special value NotImplemented: “this method does
not define comparison with that type.” Python can then try the other operand's
comparison. If neither handles equality, == falls back to identity, giving
False here. Returning False immediately would instead claim the comparison
was supported and decided.
Without the guard, other.amount on the integer 5 would raise AttributeError.
NotImplemented is a returned value, not an exception to raise, and is different
from NotImplementedError. Do not turn it into a Boolean yourself. The interpreter
uses it while resolving an operation. The data model reference
describes the other-operand and subclass-priority rules.
Choosing equality also changes collection behavior: defining __eq__ without
__hash__ makes instances of this class unhashable. That prevents a mutable
amount-based value from accidentally acting like a stable dictionary key. The
later hashing lesson
explains the equal-value/equal-hash contract. Do not restore hashing merely to
silence an error if the equality fields can change.
Hook the built-ins: __len__ and __add__
len(x) invokes the type's length protocol, which a user-defined class implements
with __len__. Special methods used by built-ins and operators are generally
looked up on the type; attaching an unrelated __len__ attribute to one instance
does not redefine len for that instance. Define these methods in the class.
__add__ returns a new Playlist rather than modifying self, matching the
non-mutating meaning we chose for +. Python permits other implementations, but
unexpectedly changing the left operand would surprise callers of this type.
The new outer list still contains references to the original tracks; concatenation
does not recursively copy them.
An unsupported addition follows a different final fallback from equality.
a + 3 lets the addition protocol try a reflected implementation such as
__radd__ where appropriate, then raises TypeError if neither operand supports
the pair. It does not fall back to identity or return False.
Step through the addition and watch a third object appear:
a and b are untouched. c is new.
For an independent check, build a Playlist from [] and another from two tracks.
Verify the combined length, each original length, and the result of comparing the
combined object with the original using is. Then try addition with a string and
confirm that it fails as an unsupported operation. Also test a broken __len__
that returns -1: a length must be a non-negative integer. Merely naming the
method does not satisfy the protocol's result contract.
Which ones are worth it
You won't implement most of them. In practice:
__repr__— almost always. It costs one line and pays back every time you debug.__eq__— when your type is a value (money, a point, a date) rather than an identity (a user session, a connection).__len__,__iter__,__getitem__— when your type genuinely wraps a collection, solen(),forand[0]mean the obvious thing.__add__and friends — rarely, and only when the operator has one obvious meaning. Clever operators are how libraries become unreadable.
Quick practice
class Card:
def __init__(self, rank):
self.rank = rank
c1 = Card(7)
c2 = Card(7)
print(c1 == c2, c1 == c1)class Basket:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
b = Basket(["soup", "bread", "milk"])
print(len(b), bool(b))🎯 Your turn
Give Account a __repr__ returning "Account(owner='Ada', balance=100)" and an
__eq__ treating two accounts as equal when owner and balance match. Then
write describe(owner, balance) returning the repr string:
describe("Ada", 100)→"Account(owner='Ada', balance=100)"describe("Sam", 0)→"Account(owner='Sam', balance=0)"
Hint — watch the quotes: the owner is quoted inside the string, the balance isn't. An f-string handles both.
The describe checks verify the representation string. Equality is exercised
separately in the value-comparison and account-audit tasks below; passing a
representation check alone does not show that comparison works.
Press ▶ Run, try the Live App chips, then ✓ Check. This one closes
the section — the practice set below builds an account that answers repr(),
len() and == like it was always part of Python.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Define Point(x, y) with a __repr__ returning "Point(1, 2)". Write show(x, y) returning repr(p).
Define Money(amount) with __eq__ comparing amounts. Write same(a, b) returning whether two Money objects are equal.
Define Playlist holding a list of tracks with __len__. Write how_many(tracks) returning len(playlist).
Define Money(amount) with __add__ returning a NEW Money holding the sum. Write total(a, b) returning the .amount of Money(a) + Money(b).
Define Account(owner, balance) holding a list history of amounts, with deposit(amount), __len__ (number of transactions), __eq__ (same owner and balance) and __repr__. Write audit(owner, amounts) returning {"repr": ..., "count": ..., "same_as_fresh": ...} — the repr, len(acct), and whether it equals a fresh account with the same owner and final balance.