Chapter 16. Operator Overloading

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 Java1

In Python, you can compute compound interest using a formula written like this:

interest = principal * ((1 + rate) ** periods - 1)

Operators that appear between operands, like 1 + rate, are infix operators. In Python, the infix operators can handle any arbitrary type. Thus, if you are dealing with real money, you can make sure that principal, rate, and periods are exact numbers—instances of the Python decimal.Decimal class—and that formula will work as written, producing an exact result.

But in Java, if you switch from float to BigDecimal to get exact results, you can’t use infix operators anymore, because they only work with the primitive types. This is the same formula coded to work with BigDecimal numbers in Java:

BigDecimal interest = principal.multiply(BigDecimal.ONE.add(rate)
                        .pow(periods).subtract(BigDecimal.ONE));

It’s clear that infix operators make formulas more readable. Operator overloading is necessary to support infix operator notation with user-defined or extension types, such as NumPy arrays. Having operator overloading in a high-level, easy-to-use language was probably a key reason for the huge success of Python in data science, including financial and scientific applications.

In “Emulating Numeric Types” ...

Get Fluent Python, 2nd Edition 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.