Operator Overloading

Learn about the concept of operator overloading and how it is applied in Python using a practical example.


Python’s operators, +, /, -, *, and so on, are implemented by special methods on classes. We can apply Python operators more widely than the built-in numbers and collection types. Doing this can be called overloading the operators: letting them work with more than the built-in types.

Looking back at the the collections.abc module section, we dropped a hint about how Python connects some built-in features with our classes. When we look at the collections.abc.Collection class, it is the abstract base class 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 operator. This operator is implemented by methods of built-in classes.

It’s not wrong to imagine the built-in len() function has this definition:

Get hands-on with 1200+ tech skills courses.