Object-oriented programming · lesson 11 of 17
Parts in this lesson
A__len__ __contains__ __iter__len, in and for
B__getitem__square brackets
C__add__what + means
Dreturn NotImplemented"I don't know this kind of value"
E__radd__+ with your object on the right

Operator overloading and the data model

Last updated

len, in, for, square brackets and + work on text, lists and numbers. They can work on your own objects too. Each one calls a dunder method, like the __eq__ and __lt__ you wrote in lesson 3.5. In this lesson you'll build a Catalogue you can measure, search and loop over, add fines together with +, keep the promise from 3.5 to check what a book is compared with, and fix sum() on a list of fines.

By the end of this lesson you can

  • Say which dunder method len, in, for, [] and + call
  • Write __len__, __contains__, __iter__ and __getitem__ for a class that holds other objects
  • Write __add__, and return NotImplemented for values it can't handle
  • Write __radd__ so sum() works on your objects

Built-in functions call dunder methods

In lesson 3.5, print called your __str__, and == called your __eq__. That's how all of Python's built-in operations work. Each one is a call to a dunder method on the object. Here are four, written both ways:

Step 1 code main.py
Edit the code, then run it again

Each line prints the same thing twice. len(title) on line 2 is really title.__len__(). "une" in title is title.__contains__("une"), and title[0] is title.__getitem__(0). Even 3 + 4 on line 5 is (3).__add__(4): the brackets around 3 stop Python reading the dot as a decimal point.

The list of these methods, and the rules for when Python calls each one, is called Python's data model. You never call them yourself: you write len(x), and Python calls x.__len__(). Giving your class one of these methods so an operator like + works on it is called operator overloading. It's polymorphism again: one len, and each kind of object answers in its own way.

What Python calls
You writePython callsIt should give back
len(x)x.__len__()A whole number, 0 or more
item in xx.__contains__(item)True or False
for item in x:x.__iter__()Something that hands out the items one by one
x[key]x.__getitem__(key)The item for that key or position
a + ba.__add__(b), then b.__radd__(a)The total
a == ba.__eq__(b) (lesson 3.5)True or False

A catalogue you can measure, search and loop over

A Catalogue holds a list of books. Without dunder methods, code would have to reach for that list: len(catalogue._books), which lesson 4.2 says not to do. With three short methods, the catalogue works like a list itself.

A catalogue that holds books, with the dunder methods Python’s built-ins call
100%
Catalogue
  • #_books: list[Book]
  • +__init__(books: list[Book])
  • +__len__(): int
  • +__contains__(title: str): bool
  • +__iter__(): list_iterator
Book
  • +title: str
  • +author: str
  • +__init__(title: str, author: str)
  • Class Book; attributes: title, author; methods: __init__.
  • Class Catalogue; attributes: _books; methods: __init__, __len__, __contains__, __iter__.
  • Catalogue holds many Book in _books.
Step 2 code main.py
Edit the code, then run it again
  • __len__ (line 11) gives back how many books there are, so len(catalogue) on line 26 works.
  • __contains__ (line 14) gets the thing after in. Here it's a title, so line 27 can ask "Emma" in catalogue. You decide what in checks.
  • __iter__ (line 17) is what for calls to start a loop. It must give back an iterator: an object that hands out the items one at a time. The built-in iter() makes one from any list, so line 18 hands the loop the catalogue's own list to walk through.

The list stays private behind _books, and the code outside reads like ordinary Python.

__getitem__

catalogue["Matilda"] calls catalogue.__getitem__("Matilda"). This catalogue keeps its books in a dict by title, made with a dict comprehension on line 9, so looking one up is one line.

Step 3 code main.py
Edit the code, then run it again

Line 19 finds Matilda and reads its author. Line 21 asks for a title that isn't there. self._by_title[title] raises KeyError, as any dict would, and line 22 catches it.

Raise the same error a built-in would raise in the same place: KeyError for a missing key, IndexError for a position past the end. Then code that already handles dicts or lists handles your object too. The NotFound error from lesson 4.8 could do both jobs, if it were made a child of both LibraryError and KeyError.

Adding fines with __add__

A member owes 75 cents for one book and 300 for another. A Fine class keeps the cents, and __add__ says what + means: a new Fine holding both amounts.

Step 4 code main.py
Edit the code, then run it again

Line 14 calls dune.__add__(emma), which makes a new Fine on line 9. dune and emma don't change, as line 16 shows: + on numbers doesn't change them either. Line 17 works because each + gives back a Fine, ready for the next +.

The limit of 500 cents from lesson 1.P is for one book's fine, so a total can be more than that.

Returning NotImplemented

What if the other side isn't a Fine? With the step 4 class, Fine(75) + 3 would reach other.cents, and stop with AttributeError: 'int' object has no attribute 'cents'. That doesn't say what really went wrong.

The fix is to check, and give back NotImplemented when the other value isn't one you know. NotImplemented is a special value built into Python, meaning "I don't know how to do this with that". It isn't an error. It tells Python to try the other side, and if that doesn't know either, Python raises a clear TypeError for you.

This is also the check lesson 3.5 promised, for comparing a book with something that isn't a book:

Step 5 code main.py
Edit the code, then run it again
  • Lines 9 and 10 give back NotImplemented unless other is a Fine.
  • Lines 20 and 21 do the same in Book.__eq__. On line 27, dune == "Dune" gets NotImplemented from the book, then from the text. When neither side knows, == falls back to asking whether they're the same object, and they aren't: False, with no error.

Change line 28 to print(Fine(75) + 3) and run it. Python stops with TypeError: unsupported operand type(s) for +: 'Fine' and 'int', which says exactly what's wrong.

Write return NotImplemented, never raise. Returning it gives the other side its turn. That turn matters in the next step.

Adding up a list of fines

sum() adds up a list. Here it's given a list of fines. Line 15 shows + works on two fines. Run it.

Step 6 code main.py
Edit the code, then run it again

Line 15 printed 375 cents, then line 16 stopped: unsupported operand type(s) for +: 'int' and 'Fine'. An int? There's no whole number in the list.

sum() starts from 0 and adds each item to it. So its first step is 0 + Fine(75). Python asks the left side first: int's __add__ doesn't know fines, so it gives back NotImplemented. Then Python asks the right side, with a method called __radd__, "add from the right". Fine has none, so there's nobody left to ask, and Python raises the TypeError.

b.__radd__(a) is called for a + b when a doesn't know how to add b. Fines only need to handle the 0 that sum() starts from: adding nothing to a fine gives the same fine.

Step 6 code main.py
Edit the code, then run it again

Now 0 + Fine(75) calls Fine(75).__radd__(0), which gives back the fine on line 15. After that, every step is fine plus fine, and line 21 prints 400 cents. Anything other than 0 on the left still gets NotImplemented on line 16.

Another way, with no __radd__, is to give sum() a place to start: sum(fines, Fine(0)). Then every step is fine plus fine.

In other languages

This step is optional. It's for anyone who will meet Java, C# or Rust later.

Operators on your own objects
PythonJavaC#Rust
+ on your own objects__add__Not allowed: write a method, a.plus(b)public static Fine operator +(Fine a, Fine b)impl Add for Fine
How many__len__, used by len()A size() methodA Count propertyA len() method
Looping over it__iter__Implement IterableImplement IEnumerableImplement IntoIterator
Square brackets__getitem__Not allowed: a get() methodAn indexer, this[...]impl Index
A value of the wrong kindreturn NotImplemented, checked when it runsCaught when compilingCaught when compilingCaught when compiling

Java has no operator overloading: + only works on numbers and text, so adding fines is a method call. C# and Rust both allow it. In Rust, + calls the add method of the Add trait, much as Python calls __add__: see Simple Rust 4.4. In all three, adding a fine to a number is caught before the program runs, which is the job NotImplemented does in Python when it runs.

Check what you learned

Three questions. Pick or type an answer, then check it.

What does this program print?
class Shelf:
    def __init__(self):
        self._books = ["Dune", "Emma"]

    def __len__(self):
        return len(self._books)


print(len(Shelf()))
What should __add__ do when the other value is a kind it doesn't know?
sum(fines) stops with unsupported operand type(s) for +: 'int' and 'Fine'. Where does the int come from?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python