6.2 Operator overloading
Python’s operators, +, /, -, *, and so on, are implemented by special methods. We can apply these operators more widely than the built-in numeric types. Doing this can be called “overloading” the operators: letting them work with more than numeric types.
Looking back at the The collections.abc module section, earlier in this chapter, we offered some foreshadowing about how Python connects some built-in features with our classes. When we look at the collections.abc.Collection class, it is the ABC for all Sized, Iterable, Containers; it requires three methods that enable two built-in functions and one built-in operator:
-
The __len__() method is used by the built-in len() function
-
The __iter__() method is used by the built-in iter() function, which means it’s used by the for statement
-
The __contains__() method is used by the built-in in...