Python course · Module 8: OOP in Python · Lesson 41 of 63
Quick answer: Dunder methods (short for “double underscore”, also called magic or special methods) are methods like __len__, __eq__ and __add__ that Python calls for you. When you write len(cart), Python runs cart.__len__(); a == b runs a.__eq__(b); a + b first tries a.__add__(b). By writing these methods in your class, your objects work with len(), in, [], for loops, comparisons, sorted() and +, just like lists and dictionaries.
In this lesson you will learn:
- what dunder methods are and how Python uses them
- how
__len__,__contains__,__getitem__and__iter__make a class act like a container - how
__eq__works, and why it makes objects unhashable - how
__lt__andfunctools.total_orderingmake objects sortable - how
__add__andNotImplementedwork for operators
Before you start: finish Lesson 40, Python Inheritance and super(): Reuse and Extend Classes. You already wrote two dunder methods, __str__ and __repr__, in Lesson 38. All examples were run on Linux with Python 3.14.6 and gave exactly the same output on Python 3.15.2, the newest release on python.org.
Table of Contents
What are dunder methods in Python?
Built-in objects support many operations: you can ask a list for its len(), check "pen" in a dictionary, or add two strings with +. A new class supports almost none of this. Here is our shopping cart with no dunder methods:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
a = ShoppingCart("Amna")
a.add_item("pen", 1.5, 4)
b = ShoppingCart("Amna")
b.add_item("pen", 1.5, 4)
print(a == b)
tests = [lambda: len(a), lambda: "pen" in a, lambda: a["pen"], lambda: a + b]
for test in tests:
try:
test()
except TypeError as err:
print("TypeError:", err)
False
TypeError: object of type 'ShoppingCart' has no len()
TypeError: argument of type 'ShoppingCart' is not a container or iterable
TypeError: 'ShoppingCart' object is not subscriptable
TypeError: unsupported operand type(s) for +: 'ShoppingCart' and 'ShoppingCart'
a == bisFalse, although both carts hold the same items. By default,==on objects only checks if they are the same object, likeisfrom Lesson 9. The data model docs say: “By default,objectimplements__eq__()by usingis“.len(),in,[]and+all fail withTypeError. (The lambdas in the loop, from Lesson 25, just let us test four operations in one loop.)
Each of these operations has a special method behind it. The data model calls this “Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators.” You never call the dunder method yourself. You write len(cart), and Python calls __len__.
__len__ and truth value: len(cart) and if cart
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def __len__(self):
return len(self.items)
cart = ShoppingCart("Amna")
print(len(cart), bool(cart))
if not cart:
print("Your cart is empty")
cart.add_item("pen", 1.5, 4)
cart.add_item("notebook", 3.0)
print(len(cart), bool(cart))
0 False
Your cart is empty
2 True
len(cart)now returns the number of different items: 0, then 2.- We did not write
__bool__, yetbool(cart)changed fromFalsetoTrue. The docs explain: when__bool__is not defined, “__len__()is called, if it is defined, and the object is considered true if its result is nonzero.” - So
if not cart:works the same way as for an empty list (truthiness was in Lesson 8).
Make a container: __contains__, __getitem__ and __iter__
Three more methods make the cart feel like a dictionary of items:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def __len__(self):
return len(self.items)
def __contains__(self, name):
return name in self.items
def __getitem__(self, name):
return self.items[name]
def __iter__(self):
return iter(self.items)
cart = ShoppingCart("Amna")
cart.add_item("pen", 1.5, 4)
cart.add_item("notebook", 3.0)
print("pen" in cart, "bag" in cart)
print(cart["pen"])
for name in cart:
price, quantity = cart[name]
print(f"{name}: {quantity} x {price}")
print(list(cart), sorted(cart))
try:
cart["bag"]
except KeyError as err:
print("KeyError:", err)
True False
(1.5, 4)
pen: 4 x 1.5
notebook: 1 x 3.0
['pen', 'notebook'] ['notebook', 'pen']
KeyError: 'bag'
"pen" in cartcalls__contains__, which the docs say should “return true if item is in self, false otherwise”.cart["pen"]calls__getitem__, which is “called to implement subscription, that is,self[subscript]“. We pass the work on to the dictionary, so a missing item raises the sameKeyError: 'bag'that a dictionary gives in Lesson 17.for name in cartcalls__iter__, which returns an iterator.iter(self.items)gives one over the item names. Nowlist(cart)andsorted(cart)work too. Lesson 44 explains iterators in detail.
Notice that each method is one short line that hands the job to self.items. That is very common: your class looks simple from outside and uses a built-in type inside.
__eq__: when are two carts equal?
You decide what “equal” means for your class. We say two carts are equal when they hold the same items, even if the owners differ:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def __eq__(self, other):
if not isinstance(other, ShoppingCart):
return NotImplemented
return self.items == other.items
a = ShoppingCart("Amna")
a.add_item("pen", 1.5, 4)
b = ShoppingCart("Bilal")
b.add_item("pen", 1.5, 4)
print(a == b, a != b, a is b)
b.add_item("notebook", 3.0)
print(a == b, a != b)
print(a == "pen")
print(ShoppingCart.__hash__)
try:
carts = {a, b}
except TypeError as err:
print("TypeError:", err)
True False False
False True
False
None
TypeError: cannot use 'ShoppingCart' as a set element (unhashable type: 'ShoppingCart')
a == bis nowTrue, buta is bis stillFalse: equal, but two separate objects.- We did not write
__ne__, yet!=works. The docs say: “For__ne__(), by default it delegates to__eq__()and inverts the result”. a == "pen"gaveFalseinstead of crashing, because__eq__returnedNotImplementedfor anything that is not a cart. The docs say a comparison method “may return the singletonNotImplementedif it does not implement the operation for a given pair of arguments”. Python then tries the other side, and when neither side can compare them,==falls back tois, which givesFalse.ShoppingCart.__hash__becameNone, so the carts cannot go into a set. The docs: “A class that overrides__eq__()and does not define__hash__()will have its__hash__()implicitly set toNone.”
Why? Sets and dictionary keys need a hash value that never changes, and the docs require that “objects which compare equal have the same hash value”. Our carts can change their items, so equal carts could later become different. Leaving them unhashable is the safe choice for objects that change. This longer error message (“cannot use … as a set element”) is from the improved error messages in Python 3.14; Lesson 18 showed the same rule for lists.
__lt__ and total_ordering: sort your objects
< calls __lt__ (“less than”). With it, sorted(), min() and max() work. We compare carts by their total:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
def __lt__(self, other):
if not isinstance(other, ShoppingCart):
return NotImplemented
return self.total() < other.total()
def __repr__(self):
return f"ShoppingCart({self.owner!r})"
amna, bilal, sara = ShoppingCart("Amna"), ShoppingCart("Bilal"), ShoppingCart("Sara")
amna.add_item("pen", 1.5, 4) # 6.0
bilal.add_item("bag", 20.0) # 20.0
sara.add_item("notebook", 3.0, 3) # 9.0
print(amna < bilal, amna > bilal)
print(sorted([bilal, sara, amna]))
print(max([bilal, sara, amna]))
try:
print(amna <= bilal)
except TypeError as err:
print("TypeError:", err)
True False
[ShoppingCart('Amna'), ShoppingCart('Sara'), ShoppingCart('Bilal')]
ShoppingCart('Bilal')
TypeError: '<=' not supported between instances of 'ShoppingCart' and 'ShoppingCart'
sorted()put the carts in order of their totals: 6.0, 9.0, 20.0, using only<.amna > bilalworked without__gt__. The docs explain that “__lt__()and__gt__()are each other’s reflection”: Python ranbilal < amnainstead.<=failed. It needs__le__(or__ge__on the other side).
Writing all six comparison methods is boring. The functools.total_ordering decorator does it for you: “The class must define one of __lt__(), __le__(), __gt__(), or __ge__(). In addition, the class should supply an __eq__() method.”
from functools import total_ordering
@total_ordering
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
def __eq__(self, other):
if not isinstance(other, ShoppingCart):
return NotImplemented
return self.total() == other.total()
def __lt__(self, other):
if not isinstance(other, ShoppingCart):
return NotImplemented
return self.total() < other.total()
amna, bilal = ShoppingCart("Amna"), ShoppingCart("Bilal")
amna.add_item("pen", 1.5, 4) # 6.0
bilal.add_item("bag", 20.0) # 20.0
print(amna <= bilal, amna >= bilal, amna == bilal)
True False False
Here __eq__ compares totals too. total_ordering builds <= from < and ==, so both must use the same rule, or the results stop making sense.
__add__: make + work
a + b first tries a.__add__(b). To be exact, the docs say Python calls type(a).__add__(a, b): it looks the method up on the class, not on the single object. We make + merge two carts into a new cart:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
if name in self.items:
quantity += self.items[name][1]
self.items[name] = (price, quantity)
def __add__(self, other):
if not isinstance(other, ShoppingCart):
return NotImplemented
merged = ShoppingCart(f"{self.owner} + {other.owner}")
for cart in (self, other):
for name, (price, quantity) in cart.items.items():
merged.add_item(name, price, quantity)
return merged
amna = ShoppingCart("Amna")
amna.add_item("pen", 1.5, 4)
bilal = ShoppingCart("Bilal")
bilal.add_item("pen", 1.5, 2)
bilal.add_item("bag", 20.0)
family = amna + bilal
print(family.owner, family.items)
print(amna.items)
try:
amna + 5
except TypeError as err:
print("TypeError:", err)
Amna + Bilal {'pen': (1.5, 6), 'bag': (20.0, 1)}
{'pen': (1.5, 4)}
TypeError: unsupported operand type(s) for +: 'ShoppingCart' and 'int'
- The pens were combined (4 + 2 = 6) and the bag was added, in a new cart called
Amna + Bilal. amna.itemsdid not change. Like+on lists and strings,__add__should return a new object and leave both sides alone.amna + 5returnedNotImplemented, so Python gave the normal error:unsupported operand type(s) for +: 'ShoppingCart' and 'int'. The docs say an arithmetic method “should returnNotImplemented” if it does not support the arguments. Because the two sides have different types, Python then tries the right side’s reflected method (hereint.__radd__), and raisesTypeErrorwhen that also returnsNotImplemented.
A complete example: a cart that works like a built-in
Here is everything in one class. Methods can use each other: __str__ calls len(self), and __add__ loops with for name in cart.
class ShoppingCart:
"""A shopping cart that works with len(), in, [], for, ==, <, + and print()."""
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
if name in self.items:
quantity += self.items[name][1]
self.items[name] = (price, quantity)
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
# text
def __repr__(self):
return f"ShoppingCart({self.owner!r})"
def __str__(self):
return f"{self.owner}'s cart: {len(self)} items, total {self.total():.2f}"
# container behaviour
def __len__(self):
return len(self.items)
def __contains__(self, name):
return name in self.items
def __getitem__(self, name):
return self.items[name]
def __iter__(self):
return iter(self.items)
# comparing and adding
def __eq__(self, other):
if not isinstance(other, ShoppingCart):
return NotImplemented
return self.items == other.items
def __lt__(self, other):
if not isinstance(other, ShoppingCart):
return NotImplemented
return self.total() < other.total()
def __add__(self, other):
if not isinstance(other, ShoppingCart):
return NotImplemented
merged = ShoppingCart(f"{self.owner} + {other.owner}")
for cart in (self, other):
for name in cart:
price, quantity = cart[name]
merged.add_item(name, price, quantity)
return merged
amna = ShoppingCart("Amna")
amna.add_item("pen", 1.5, 4)
amna.add_item("notebook", 3.0)
bilal = ShoppingCart("Bilal")
bilal.add_item("bag", 20.0)
print(amna)
print(len(amna), "pen" in amna, amna["notebook"])
print(amna == bilal, amna < bilal)
family = amna + bilal
print(family)
print(sorted([family, bilal, amna]))
Amna's cart: 2 items, total 9.00
2 True (3.0, 1)
False True
Amna + Bilal's cart: 3 items, total 29.00
[ShoppingCart('Amna'), ShoppingCart('Bilal'), ShoppingCart('Amna + Bilal')]

len(amna)is 2,"pen" in amnaisTrue, andamna["notebook"]is(3.0, 1).amna == bilalisFalse(different items), andamna < bilalisTrue(9.00 is less than 20.00).amna + bilalmade a 3-item cart worth 29.00, andsorted()placed it last.
We left out total_ordering here on purpose: __eq__ compares items but __lt__ compares totals, so <= built from them would mix two rules. Dunder methods are also inherited like any other method (Lesson 40), so a subclass of this cart gets all of them. In Lesson 42, dataclasses write __init__, __repr__ and __eq__ for you.
Try it yourself
Exercise 1: A playlist
Write a Playlist class with a name, a list of songs and an add() method. Add __len__, __contains__ and __str__ ("Study: 2 songs"). Show that an empty playlist is false.
Exercise 2: Money
Write a Money class with an amount. Add __eq__, __add__ (returns a new Money) and __repr__. Check that Money(1.5) + Money(3) == Money(4.5) is True, that Money(4.5) == 4.5 is False, and that Money(1) + 2 raises TypeError.
Exercise 3: Sortable products
Write a Product class with name and price, compared by price. Use total_ordering so that sorted(), max(), min() and <= all work.
Solutions
Solution 1
class Playlist:
def __init__(self, name):
self.name = name
self.songs = []
def add(self, song):
self.songs.append(song)
def __len__(self):
return len(self.songs)
def __contains__(self, song):
return song in self.songs
def __str__(self):
return f"{self.name}: {len(self)} songs"
study = Playlist("Study")
print(study, bool(study))
study.add("Rain sounds")
study.add("Lo-fi beat")
print(study, bool(study))
print("Rain sounds" in study, "Fast beat" in study)
Study: 0 songs False
Study: 2 songs True
True False
__len__ alone makes an empty playlist false, and __str__ reuses len(self).
Solution 2
class Money:
def __init__(self, amount):
self.amount = amount
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return self.amount == other.amount
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(self.amount + other.amount)
def __repr__(self):
return f"Money({self.amount})"
price = Money(1.5) + Money(3)
print(price)
print(price == Money(4.5), price == 4.5)
try:
Money(1) + 2
except TypeError as err:
print("TypeError:", err)
Money(4.5)
True False
TypeError: unsupported operand type(s) for +: 'Money' and 'int'
Returning NotImplemented for other types gives False for == and the normal TypeError for +.
Solution 3
from functools import total_ordering
@total_ordering
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __eq__(self, other):
if not isinstance(other, Product):
return NotImplemented
return self.price == other.price
def __lt__(self, other):
if not isinstance(other, Product):
return NotImplemented
return self.price < other.price
def __repr__(self):
return f"{self.name}({self.price})"
products = [Product("bag", 20.0), Product("pen", 1.5), Product("notebook", 3.0)]
print(sorted(products))
print(max(products), min(products))
print(Product("pen", 1.5) <= Product("ruler", 1.5))
[pen(1.5), notebook(3.0), bag(20.0)]
bag(20.0) pen(1.5)
True
total_ordering built <= from __lt__ and __eq__; both use the price, so a 1.50 pen is <= a 1.50 ruler.
Common mistakes
- Returning the wrong type from
__len__. It must return a whole number of 0 or more. Returning a total like 6.0 givesTypeError: 'float' object cannot be interpreted as an integer. - Using objects with
__eq__as dictionary keys. After you add__eq__,{cart: "Monday"}fails withTypeError: cannot use 'ShoppingCart' as a dict key (unhashable type: 'ShoppingCart'). Use a hashable key, such as the owner’s name. - No type check in
__eq__.return self.items == other.itemscrashes oncart == "pen":AttributeError: 'str' object has no attribute 'items'. Check withisinstance()and returnNotImplemented. - Changing
selfin__add__.self.items.update(other.items)followed byreturn selfchanges Amna’s own cart, andfamily is amnaprintedTrue. Build and return a new object. - A typo in the name.
def __len(self):(no underscores at the end) is just a normal method, solen(cart)still saysTypeError: object of type 'ShoppingCart' has no len().
Frequently asked questions
Why are they called dunder or magic methods?
“Dunder” is short for “double underscore”, because the names start and end with two underscores, like __init__. They are sometimes called magic methods because Python calls them automatically. The official docs call them special methods.
Should I call dunder methods directly?
Normally no. Write len(cart), a == b and a + b, and let Python call __len__, __eq__ and __add__. The operators also handle extra steps for you, such as trying the other side when you return NotImplemented. Inside a subclass, super().__init__() is the common exception.
What is the difference between __str__ and __repr__?
__str__ gives friendly text for users and is used by print(). __repr__ gives precise text for programmers, is used when you print a list of objects, and should look like the code that creates the object. Lesson 38 covers both with examples.
Summary
- Dunder methods let Python’s operators and built-in functions work with your objects:
len()calls__len__,incalls__contains__,[]calls__getitem__,forcalls__iter__. __len__also decides truth: an object with length 0 is false.__eq__defines equality;!=comes free, but the class becomes unhashable unless you also define__hash__.__lt__makes objects sortable;functools.total_orderingadds the other comparisons from__lt__and__eq__.- Return
NotImplementedfor types you do not support, and make__add__return a new object.
Next lesson
Next: Lesson 42, Python dataclasses: Write Classes With Less Code.
Sources
- Data model: special method names (Python docs)
- functools.total_ordering (Python docs)
- What’s New in Python 3.14: improved error messages
- dataclasses (Python docs)
- Python downloads page (python.org)





