Intermediate   Chapter 135 · 30 min read · Module 10: Object-Oriented Programming

Operator Overloading

Learning objectives
  • After this chapter you can explain what operator overloading means.
  • You can overload arithmetic operators with __add__, __sub__ and __mul__.
  • You can define comparison with __eq__ and __lt__ so objects can be compared and sorted.
  • You can return NotImplemented for unsupported types.
  • You can support in-place operators and reflected operators like __radd__.

In Python the plus sign does different jobs. It adds numbers, joins strings and merges lists. The same symbol works because each type decides what + means for itself. You can give your own classes the same power. This is called operator overloading.

Suppose you write a Vector class. Without overloading, you must write v1.add(v2). With overloading you write v1 + v2, which is shorter and reads like maths. The result is code that is closer to how people think about the problem.

Operator overloading is built on the magic methods from the last chapter. Every operator has a matching method name. When Python meets an operator, it calls that method on the left operand. In this chapter you will learn the most common ones and the rules for using them well.

What is operator overloading?

Operator overloading means defining what an operator does when it is used with objects of your class. You do not change the operator itself. You only write the special method that Python calls for it. When Python sees a + b, it runs a.__add__(b). If your class has that method, your code runs and its return value becomes the result.

Operator overloading: giving an operator a custom meaning for the objects of a class by defining its special method
OperatorMethodOperatorMethod
+__add__==__eq__
-__sub__!=__ne__
*__mul__<__lt__
/__truediv__<=__le__
//__floordiv__>__gt__
%__mod__>=__ge__
**__pow__-x__neg__
+=__iadd__abs(x)__abs__

Arithmetic operators

An arithmetic method takes self (the left side) and other (the right side). It should usually build and return a new object and leave both inputs unchanged, just like adding two numbers does not change them. Combine this with __repr__ so results are easy to see.

Example 1: a 2D vector
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)

    def __mul__(self, k):
        return Vector(self.x * k, self.y * k)

    def __neg__(self):
        return Vector(-self.x, -self.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

a = Vector(1, 2)
b = Vector(4, 6)
print(a + b)
print(b - a)
print(a * 3)
print(-a)
Vector(5, 8) Vector(3, 4) Vector(3, 6) Vector(-1, -2)

Comparison operators

By default, == on your objects checks identity: two different objects are never equal, even with the same data. Define __eq__ to compare the data instead. For ordering, define __lt__ (less than). Python's sorted() and min() only need __lt__. If you define __eq__, Python sets __hash__ to None, so objects become unhashable unless you also write __hash__. In Python 3.7+ the functools.total_ordering decorator can fill in the other comparisons from __eq__ and one ordering method.

Example 2: equality and sorting
class Money:
    def __init__(self, amount):
        self.amount = amount

    def __eq__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return self.amount == other.amount

    def __lt__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return self.amount < other.amount

    def __repr__(self):
        return f"Money({self.amount})"

print(Money(5) == Money(5))
print(Money(5) == Money(7))
print(Money(3) < Money(9))
print(sorted([Money(30), Money(10), Money(20)]))
print(Money(5) == 5)
True False True [Money(10), Money(20), Money(30)] False

Returning NotImplemented (not the exception NotImplementedError) tells Python: I do not know how to handle this type. Python then tries the other operand, and if nobody can handle it, it falls back to a default answer for == or raises TypeError for other operators. That is why Money(5) == 5 printed False above.

Reflected and in-place operators

What about 3 * v where the left side is an int? The int does not know your class, so Python tries the right operand's reflected method __rmul__. For addition it is __radd__. This is also how sum() works with your objects, since it starts from the number 0. In-place operators like += call __iadd__. If you do not write it, Python falls back to __add__ and rebinds the name to the new object.

Example 3: reflected add and sum()
class Score:
    def __init__(self, v):
        self.v = v

    def __add__(self, other):
        if isinstance(other, Score):
            return Score(self.v + other.v)
        return Score(self.v + other)

    def __radd__(self, other):
        return self.__add__(other)

    def __repr__(self):
        return f"Score({self.v})"

print(Score(2) + 5)
print(5 + Score(2))
print(sum([Score(1), Score(2), Score(3)]))
Score(7) Score(7) Score(6)
Use operator overloading only when the meaning is natural. Adding two vectors or two money amounts is clear. Using + to mean something surprising, like sending an email, makes code hard to read.

Good design rules

  • Return a new object from arithmetic operators instead of changing self.
  • Return NotImplemented for types you cannot handle.
  • Keep operators consistent: if a == b is True, a != b should be False.
  • Write __repr__ so results can be printed during testing.
  • Avoid overloading when a clearly named method is more readable.

With these rules your classes can feel as natural as built-in numbers. Libraries such as NumPy, pandas and pathlib use operator overloading heavily. For example, in pathlib the slash operator joins path pieces, which is a good illustration of an operator chosen well.

Python syntax

Syntax
class C:
    def __add__(self, other): ...
    def __radd__(self, other): ...
    def __eq__(self, other): ...
    def __lt__(self, other): ...
    def __neg__(self): ...

Real-world applications

  • Mathematical classes such as vectors, matrices, fractions and complex numbers
  • Money, time and measurement units where addition and comparison make sense
  • Sorting custom objects with sorted(), min() and max()
  • Path-like or query-like objects with friendly operators
  • Data libraries that combine arrays and tables with plain operators

Common mistakes

Mistake: Changing self inside __add__ and returning it
Fix: Create and return a new object so that a + b does not modify a.
Mistake: Raising NotImplementedError instead of returning NotImplemented
Fix: Return the NotImplemented value; the exception stops the program and blocks the right operand from trying.
Mistake: Defining __eq__ and then using the object in a set or dict key
Fix: Also define __hash__ using the same fields, or avoid hashing; a class with __eq__ but no __hash__ is unhashable.
Mistake: Assuming 5 + obj works when only __add__ exists
Fix: Add __radd__ for the case where the left operand is a built-in type.

Important tips

  • Start with __repr__, __eq__ and __add__ then grow.
  • Use functools.total_ordering to avoid writing all six comparisons.
  • Check types with isinstance before using other's attributes.
  • Write a few small tests of the operators.
  • Prefer clear method names when an operator would be confusing.

Key points summary

  • Each operator maps to a dunder method.
  • The left operand's method is tried first, then the right one's reflected method.
  • __eq__ compares data; the default compares identity.
  • Sorting needs __lt__.
  • Return NotImplemented, not raise NotImplementedError.

Exam and interview points

  • a + b calls a.__add__(b); if that returns NotImplemented, b.__radd__(a) is tried.
  • Defining __eq__ without __hash__ makes instances unhashable.
  • NotImplemented is a value; NotImplementedError is an exception.
  • Comparison methods should return True or False (or NotImplemented).

Quick revision

  • + is __add__
  • == is __eq__
  • < is __lt__
  • -x is __neg__
  • Reflected: __radd__
  • Return a new object

Frequently asked questions

Can I create new operators?

No. You can only give new meaning to existing operators such as +, -, ==. Python does not allow brand new symbols.

Why did my object become unhashable?

When a class defines __eq__ without __hash__, Python sets __hash__ to None. Add a __hash__ that uses the same fields as __eq__.

Do I need both __lt__ and __gt__?

Not for sorted() and min(), since they use __lt__. If you need all comparisons, use functools.total_ordering with __eq__ and one ordering method.

What is the difference between __add__ and __iadd__?

__add__ builds a new object for a + b. __iadd__ handles a += b and may change the object in place. If it is missing, Python uses __add__.

What does NotImplemented do?

It tells Python this operand cannot handle the operation. Python then tries the other operand, and finally raises TypeError for most operators.

Practise this chapter

18 practice questions Take the chapter quiz

Related chapters