Chapter 30. Operator Overloading
This chapter continues our in-depth survey of class mechanics by focusing on operator overloading. We looked briefly at operator overloading in prior chapters. Here, we’ll fill in more details and explore a handful of commonly used overloading methods, most of which we haven’t yet encountered. Although we don’t have space to demonstrate each of the many operator-overloading methods available, those we will code here are a representative sample large enough to uncover the possibilities of this Python class feature.
The Basics
Really “operator overloading” simply means intercepting built-in operations in a class’s methods—Python automatically invokes your methods when instances of the class appear in built-in operations, and your method’s return value becomes the result of the corresponding operation. Here’s a review of the key ideas behind overloading:
Operator overloading lets classes intercept normal Python operations.
Classes can overload all Python built-in expression operators.
Classes can also overload other built-in operations such as printing, function calls, and attribute access.
Overloading is implemented by providing specially named methods in a class.
Python predefines the special method names that correspond to built-in operations.
In other words, when methods of predefined special names are provided in a class, Python automatically calls them when instances of the class appear in their associated built-in operations or expressions. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access