Track 11 · Lesson 10 of 12
Special methods
Make your objects work with ==, <, sorted(), len(), in, for loops and + by implementing Python's special methods.
You will be able to
- Explain how built-in operations such as len() and == call special methods
- Implement __eq__ for value equality, returning NotImplemented for unrelated types
- Implement __lt__ and use functools.total_ordering so objects can be sorted
- Make a class behave like a container with __len__, __contains__, __iter__ and __getitem__
- Overload + with __add__ (and __radd__ so sum() works)
Included with a Formula Quest membership
It has 5 graded exercises with feedback, hints and solutions. Python Quest is included in Formula Quest memberships that cover Python; membership and billing are managed on Formula Quest.
View Formula Quest memberships
Tracks 1 and 2, the first lesson of every track, the playground and the dataset library are free.