10.10 Operator Overloading

You’ve seen that you can interact with objects by accessing their attributes and properties and by calling their methods. Method-call notation can be cumbersome for certain kinds of operations, such as arithmetic. In these cases, it would be more convenient to use Python’s rich set of built-in operators.

This section shows how to use operator overloading to define how Python’s operators should handle objects of your own types. You’ve already used operator overloading frequently across wide ranges of types. For example, you’ve used:

  • the + operator for adding numeric values, concatenating lists, concatenating strings and adding a value to every element in a NumPy array.

  • the [] operator for accessing elements in lists, ...

Get Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and The Cloud now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.