Lesson 26 of 34 · Classes & OOP
Python Dunder Methods: __str__, __repr__ and __eq__
Why does len() work on lists, + on numbers and print() on almost anything? Because those objects implement special methods whose names start and end with double underscores — dunder methods (also called magic methods). Define them in your own classes, and your objects plug straight into Python's built-in syntax.
The problem
Without dunder methods, objects print unhelpfully and compare by identity:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
v = Vector(1, 2)
print(v) # <__main__.Vector object at 0x7f3a...>
print(Vector(1, 2) == Vector(1, 2)) # False — two different objects
__str__: for humans
__str__ returns the friendly text used by print(), str() and f-strings:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
print(Vector(1, 2)) # (1, 2)
print(f"Moving {Vector(0, 3)}") # Moving (0, 3)
__repr__: for developers
__repr__ returns an unambiguous description for debugging. The convention is to make it look like the code that would recreate the object. Python uses it in the interactive shell, in error messages, in debuggers — and when your object sits inside a list or dictionary. Add it to the Vector class:
def __repr__(self):
return f"Vector({self.x!r}, {self.y!r})"
print(repr(Vector(1, 2))) # Vector(1, 2)
print([Vector(1, 2)]) # [Vector(1, 2)] <- containers use repr
The !r conversion inside an f-string applies repr() to a value, which adds quotes around strings: f"{'USD'!r}" gives 'USD'. If a class defines only __repr__, str() falls back to it — so __repr__ is the one to write first.
__eq__: value equality
By default == checks whether two names refer to the same object. Add an __eq__ method to compare values instead:
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return self.x == other.x and self.y == other.y
print(Vector(1, 2) == Vector(1, 2)) # True
print(Vector(1, 2) == (1, 2)) # False
Returning the special value NotImplemented tells Python "I don't know how to compare with that type". Python then tries the other object's method, and if nobody knows, == simply returns False. One side effect: a class that defines __eq__ without __hash__ becomes unhashable, so its instances can't go into sets or be used as dictionary keys.
Operators and more
Many operators and built-ins map to dunder methods:
| You write | Python calls |
|---|---|
a + b |
a.__add__(b) |
a - b, a * b |
__sub__, __mul__ |
a < b |
a.__lt__(b) — enables sorted() |
len(a) |
a.__len__() |
x in a |
a.__contains__(x) |
bool(a), if a: |
a.__bool__() |
Here is __add__ for our Vector:
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
print(Vector(1, 2) + Vector(3, 4)) # (4, 6)
Operators should return a new object and leave both operands unchanged. If __add__ returns NotImplemented and the other operand can't help either, Python raises TypeError: unsupported operand type(s).
Common mistakes
- Printing inside
__str__: it must return a string; returningNoneraisesTypeError: __str__ returned non-string. - Misspelled dunders:
__stror_repr_are just ordinary methods that Python never calls. - Raising an error or returning
Falsefor unknown types instead of returningNotImplemented. - Mutating
selfin__add__instead of returning a new object.
Assignment
Complete the Money class (the initializer is already written) with four dunder methods:
__repr__returns"Money(<amount>, '<currency>')", e.g.Money(5, 'USD')— use!rfor both values.__str__returns the amount with two decimals and the currency, e.g."5.00 USD".__eq__treats twoMoneyobjects as equal when both amount and currency match. Comparing with anything that isn'tMoneyreturnsNotImplemented, soMoney(5) == 5isFalse.__add__returns a newMoneywith the summed amount when both have the same currency. For different currencies — or non-Moneyvalues — it returnsNotImplemented, so Python raises aTypeError.
Money(5, "USD") # repr: Money(5, 'USD')
str(Money(3.5, "EUR")) # "3.50 EUR"
Money(5) == Money(5, "USD") # True (USD is the default)
Money(5, "USD") + Money(2.5, "USD") # Money(7.5, 'USD')
Money(1, "USD") + Money(1, "EUR") # TypeErrorPremium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .