Skip to Content
Fluent Python
book

Fluent Python

by Luciano Ramalho
August 2015
Intermediate
790 pages
18h 48m
English
O'Reilly Media, Inc.
Content preview from Fluent Python

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

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.
Start your free trial

You might also like

Fluent Python, 2nd Edition

Fluent Python, 2nd Edition

Luciano Ramalho

Publisher Resources

ISBN: 9781491946237Errata Page