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 returnNotImplementedfor values it can't handle - Write
__radd__sosum()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:
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.
| You write | Python calls | It should give back |
|---|---|---|
len(x) | x.__len__() | A whole number, 0 or more |
item in x | x.__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 + b | a.__add__(b), then b.__radd__(a) | The total |
a == b | a.__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.
- #_books: list[Book]
- +__init__(books: list[Book])
- +__len__(): int
- +__contains__(title: str): bool
- +__iter__(): list_iterator
- +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.
__len__(line 11) gives back how many books there are, solen(catalogue)on line 26 works.__contains__(line 14) gets the thing afterin. Here it's a title, so line 27 can ask"Emma" in catalogue. You decide whatinchecks.__iter__(line 17) is whatforcalls to start a loop. It must give back an iterator: an object that hands out the items one at a time. The built-initer()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.
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.
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:
- Lines 9 and 10 give back
NotImplementedunlessotheris aFine. - Lines 20 and 21 do the same in
Book.__eq__. On line 27,dune == "Dune"getsNotImplementedfrom 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.
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.
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.
| Python | Java | C# | 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() method | A Count property | A len() method |
| Looping over it | __iter__ | Implement Iterable | Implement IEnumerable | Implement IntoIterator |
| Square brackets | __getitem__ | Not allowed: a get() method | An indexer, this[...] | impl Index |
| A value of the wrong kind | return NotImplemented, checked when it runs | Caught when compiling | Caught when compiling | Caught 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.
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.
- The Python Language Reference: Emulating container types: __len__, __getitem__, __iter__ and __contains__
- The Python Language Reference: Emulating numeric types: __add__ and the other operators
- The Python Language Reference: object.__radd__: when Python calls the reflected method
- Built-in Constants: NotImplemented
- Built-in Functions: iter
- Built-in Functions: sum: starts from 0 unless you give a start value
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- The Java Language Specification: 15.18 Additive Operators: Java’s + works on numbers and text only
- C# documentation: Operator overloading: operators on your own types in C#
- C# documentation: Indexers: square brackets on your own types in C#
- Rust standard library: std::ops: operators on your own types in Rust, through traits