Chapter 13. Operator Overloading: Doing It Right
There are some things that I kind of feel torn about, like operator overloading. I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++.1
James Gosling, Creator of Java
Operator overloading allows user-defined objects to interoperate with infix operators such as + and | or unary operators like - and ~. More generally, function invocation (()), attribute access (.), and item access/slicing ([]) are also operators in Python, but this chapter covers unary and infix operators.
In “Emulating Numeric Types” (Chapter 1) we saw some trivial implementations of operators in a bare bones Vector class. The __add__ and __mul__ methods in Example 1-2 were written to show how special methods support operator overloading, but there are subtle problems in their implementations that we overlooked. Also, in Example 9-2, we noted that the Vector2d.__eq__ method considers this to be True: Vector(3, 4) == [3, 4]—which may or not make sense. We will address those matters in this chapter.
In the following sections, we will cover:
-
How Python supports infix operators with operands of different types
-
Using duck typing or explicit type checks to deal with operands of various types
-
How an infix operator method should signal it cannot handle an operand
-
The special behavior of the rich comparison operators (e.g.,
==,>,<=, etc.) -
The default handling of augmented assignment operators, like