Search⌘ K
AI Features

Operator Overloading

Explore operator overloading in Python by understanding how special methods enable operators like + and / to work with custom classes. Learn about abstract base classes, duck typing, and how to implement mutable and immutable data objects using Python's operator methods. This lesson helps you grasp how to extend Python's syntax for more intuitive object interactions.

Overview

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:

Python 3.10.4
def len(object: Sized) -> int:
return object.__len__()

When we ask for len(x), it’s doing the same thing as x.__len__(), but is shorter, easier to read, and easier to remember. Similarly, iter(y) is effectively y.__iter__(). And an expression like z in ...