Part 09 / Topic 8 of 12
Dunder (magic) methods
Dunder methods have double underscores on both sides, like __init__. Python calls them for you when you use built-in features:
| You write | Python calls | Use it for |
|---|---|---|
str(obj), print(obj), f-string |
__str__ |
Friendly text for users |
repr(obj), the REPL, inside lists |
__repr__ |
Clear text for developers, ideally looks like code |
a == b |
__eq__ |
Equality by value |
a < b, sorted(...) |
__lt__ |
Ordering and sorting |
len(obj) |
__len__ |
Size |
a + b |
__add__ |
The + operator |
Think of a TV remote: you press "Volume +" and the TV decides what that means. With dunders, your class decides what + or len() means for it.
__str__ vs __repr__
class Book:
def __init__(self, title: str, price: int):
self.title = title
self.price = price
def __str__(self) -> str:
return f"{self.title} (₹{self.price})"
def __repr__(self) -> str:
return f"Book({self.title!r}, {self.price})"
book = Book("Wings of Fire", 299)
print(book) # Wings of Fire (₹299)
print(repr(book)) # Book('Wings of Fire', 299)
print([book]) # [Book('Wings of Fire', 299)] (lists use __repr__)
!r inside an f-string uses repr(), so the title gets its quotes. If you write only one, write __repr__: print falls back to it.
__eq__, __lt__ and sorting
By default == checks if two names point to the same object. Write __eq__ to compare by value. Write __lt__ (less than) and sorted() can sort your objects.
class Book:
def __init__(self, title: str, price: int):
self.title = title
self.price = price
def __repr__(self) -> str:
return f"Book({self.title!r}, {self.price})"
def __eq__(self, other) -> bool:
return self.title == other.title and self.price == other.price
def __lt__(self, other) -> bool:
return self.price < other.price # cheaper book comes first
a = Book("Godaan", 250)
b = Book("Godaan", 250)
print(a == b) # True (same values)
shelf = [Book("Gitanjali", 199), Book("Malgudi Days", 350), a]
print(sorted(shelf))
# [Book('Gitanjali', 199), Book('Godaan', 250), Book('Malgudi Days', 350)]
__len__ and __add__ (operator overloading)
Operator overloading means giving an operator like + a meaning for your own class.
class Cart:
def __init__(self, items: list[str]):
self.items = items
def __len__(self) -> int:
return len(self.items)
def __add__(self, other): # cart + cart -> a new merged cart
return Cart(self.items + other.items)
mine = Cart(["Rice", "Dal"])
yours = Cart(["Milk"])
both = mine + yours
print(len(both)) # 3
print(both.items) # ['Rice', 'Dal', 'Milk']
No method overloading in Python
In some languages you can write two methods with the same name but different parameters (method overloading). In Python the second def simply replaces the first. Use default arguments or *args (Part 5) instead.
class Calculator:
def add(self, *numbers: float) -> float: # one method, any number of values
return sum(numbers)
def area(self, length: float, width: float | None = None) -> float:
if width is None: # one value -> square
return length * length
return length * width # two values -> rectangle
calc = Calculator()
print(calc.add(2, 3), calc.add(2, 3, 5)) # 5 10
print(calc.area(4), calc.area(4, 6)) # 16 24
Full program: examples/04_book_shop_dunders.py.
🔍 Going deeper: writing
__eq__makes objects unhashable (nosetor dict key) unless you also write__hash__. A@dataclass(frozen=True)(section 10) does this for you.functools.total_orderingcan fill in<=,>,>=from__eq__and__lt__.
Done here? The practice set for Part 9 — 8 exercises with solutions — is on the part page.