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++.
— James Gosling Creator of Java
Operator overloading allows user-defined objects to interoperate with infix operators such as
| or unary operators like
~. 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
__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
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:
+=, and how to ...