Skip to main content
Editor

Python Operator Overloading: Make Classes Work with +, -, ==

Advanced25 min6 exercises95 XP
0/6 exercises

The + operator means different things in different contexts. 3 + 5 gives you 8. 'hello' + ' world' gives you 'hello world'. [1, 2] + [3, 4] gives you [1, 2, 3, 4]. Same symbol, completely different behavior.

How does Python know what + should do? It asks the object on the left side by calling its __add__ method. Integers define __add__ to do math. Strings define it to concatenate. Lists define it to merge.

In this tutorial, you'll learn how to define these methods in your own classes. By the end, your custom objects will work with +, -, *, ==, <, +=, and more - just like built-in types.

How Do Arithmetic Operators Work with Custom Classes?

Each arithmetic operator maps to a specific magic method. When you write a + b, Python calls a.__add__(b). When you write a - b, Python calls a.__sub__(b). Here's the full mapping:

Operators are just method calls
# Operator -> Magic Method
# a + b -> a.__add__(b)
# a - b -> a.__sub__(b)
# a * b -> a.__mul__(b)
# a / b -> a.__truediv__(b)
# a // b -> a.__floordiv__(b)
# a % b -> a.__mod__(b)
# a ** b -> a.__pow__(b)
# Let's prove it:
print(5 + 3) # 8
print((5).__add__(3)) # 8 (same thing!)
print('hi' + '!') # hi!
print('hi'.__add__('!')) # hi! (same thing!)
Output
8
8
hi!
hi!

Let's build a Money class where + combines amounts and - finds the difference.

A Money class with +, -, and *
class Money:
def __init__(self, amount, currency='USD'):
self.amount = round(amount, 2)
self.currency = currency
def __add__(self, other):
if self.currency != other.currency:
raise ValueError('Cannot add different currencies')
return Money(self.amount + other.amount, self.currency)
def __sub__(self, other):
if self.currency != other.currency:
raise ValueError('Cannot subtract different currencies')
return Money(self.amount - other.amount, self.currency)
def __mul__(self, factor):
return Money(self.amount * factor, self.currency)
def __repr__(self):
return f'${self.amount:.2f} {self.currency}'
price = Money(29.99)
tax = Money(2.40)
total = price + tax
print(total) # $32.39 USD
change = Money(50) - total
print(change) # $17.61 USD
bulk = price * 3
print(bulk) # $89.97 USD
Output
$32.39 USD
$17.61 USD
$89.97 USD

What Are Reflected Operators Like __radd__?

What happens when you write 3 * money? Python first tries (3).__mul__(money). But integers don't know about your Money class, so __mul__ returns NotImplemented. Python then tries the reflected version: money.__rmul__(3).

Reflected operators have an r prefix: __radd__, __rsub__, __rmul__, etc. They handle the case where your object is on the right side of the operator.

Reflected operators handle reversed operands
class Money:
def __init__(self, amount, currency='USD'):
self.amount = round(amount, 2)
self.currency = currency
def __mul__(self, factor):
return Money(self.amount * factor, self.currency)
def __rmul__(self, factor):
return self.__mul__(factor)
def __repr__(self):
return f'${self.amount:.2f} {self.currency}'
price = Money(9.99)
print(price * 5) # $49.95 USD (calls __mul__)
print(5 * price) # $49.95 USD (calls __rmul__)
Output
$49.95 USD
$49.95 USD

How Do Comparison Operators Work?

Comparison operators follow the same pattern as arithmetic ones. Each operator calls a specific magic method:

Comparison operators for a Temperature class
# Operator -> Magic Method
# a == b -> a.__eq__(b)
# a != b -> a.__ne__(b)
# a < b -> a.__lt__(b)
# a <= b -> a.__le__(b)
# a > b -> a.__gt__(b)
# a >= b -> a.__ge__(b)
class Temperature:
def __init__(self, fahrenheit):
self.fahrenheit = fahrenheit
def __eq__(self, other):
if not isinstance(other, Temperature):
return NotImplemented
return self.fahrenheit == other.fahrenheit
def __lt__(self, other):
if not isinstance(other, Temperature):
return NotImplemented
return self.fahrenheit < other.fahrenheit
def __le__(self, other):
return self == other or self < other
def __repr__(self):
return f'{self.fahrenheit}°F'
freezing = Temperature(32)
boiling = Temperature(212)
room = Temperature(72)
print(freezing < boiling) # True
print(freezing == Temperature(32)) # True
print(room <= boiling) # True
Output
True
True
True
@total_ordering generates missing comparisons
from functools import total_ordering
@total_ordering
class Score:
def __init__(self, points):
self.points = points
def __eq__(self, other):
if not isinstance(other, Score):
return NotImplemented
return self.points == other.points
def __lt__(self, other):
if not isinstance(other, Score):
return NotImplemented
return self.points < other.points
def __repr__(self):
return f'Score({self.points})'
a = Score(85)
b = Score(92)
print(a < b) # True
print(a > b) # False (auto-generated!)
print(a >= b) # False (auto-generated!)
print(a != b) # True (auto-generated!)
Output
True
False
False
True

What Are In-Place Operators Like __iadd__?

In-place operators like +=, -=, and *= are different from regular ones. a += b is not always the same as a = a + b. With __iadd__, you can modify the object in place instead of creating a new one.

This matters for performance when modifying large objects. Lists use this optimization: my_list += [4, 5] modifies the list in place, while my_list = my_list + [4, 5] creates an entirely new list.

In-place operators modify the object
class Inventory:
def __init__(self, items=None):
self.items = items or []
def __iadd__(self, item):
self.items.append(item)
return self # Must return self for in-place!
def __isub__(self, item):
if item in self.items:
self.items.remove(item)
return self
def __repr__(self):
return f'Inventory({self.items})'
bag = Inventory()
bag += 'Sword'
bag += 'Shield'
bag += 'Potion'
print(bag) # Inventory(['Sword', 'Shield', 'Potion'])
bag -= 'Shield'
print(bag) # Inventory(['Sword', 'Potion'])
Output
Inventory(['Sword', 'Shield', 'Potion'])
Inventory(['Sword', 'Potion'])

If you don't define __iadd__, Python falls back to __add__. So a += b becomes a = a.__add__(b) - creating a new object. This is fine for immutable types, but wasteful for mutable ones.

How Do You Build a Complete Vector Class?

Let's put everything together by building a 2D Vector class that supports addition, subtraction, multiplication (by a scalar), equality, comparisons (by length), and in-place operations.

A complete Vector class with operator overloading
import math
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
# Arithmetic
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, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __rmul__(self, scalar):
return self.__mul__(scalar)
# In-place
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
# Comparison
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return self.x == other.x and self.y == other.y
def __lt__(self, other):
return self.length < other.length
# Utilities
@property
def length(self):
return math.sqrt(self.x ** 2 + self.y ** 2)
def __repr__(self):
return f'Vector({self.x}, {self.y})'
# Test it out
a = Vector(3, 4)
b = Vector(1, 2)
print(a + b) # Vector(4, 6)
print(a - b) # Vector(2, 2)
print(a * 2) # Vector(6, 8)
print(3 * b) # Vector(3, 6)
print(a == Vector(3, 4)) # True
print(a < Vector(10, 10)) # True (5.0 < 14.14)
print(f'Length of a: {a.length:.2f}') # 5.00
Output
Vector(4, 6)
Vector(2, 2)
Vector(6, 8)
Vector(3, 6)
True
True
Length of a: 5.00

Notice how the Vector class uses @property for length (a computed attribute from the previous tutorial) and how __lt__ compares vectors by their length. This is a natural way to define "less than" for vectors.

What Are the Most Common Operator Overloading Patterns?

Here is a quick reference of the most important operator methods you'll use. You don't need to memorize all of them - just know they exist so you can look them up when needed.

Operator overloading cheat sheet
# Arithmetic operators
# __add__(self, other) -> self + other
# __sub__(self, other) -> self - other
# __mul__(self, other) -> self * other
# __truediv__(self, other) -> self / other
# __mod__(self, other) -> self % other
# __pow__(self, other) -> self ** other
# __neg__(self) -> -self
# __abs__(self) -> abs(self)
# Reflected (right-side) operators
# __radd__, __rsub__, __rmul__, __rtruediv__
# In-place operators
# __iadd__, __isub__, __imul__, __itruediv__
# Comparison operators
# __eq__, __ne__, __lt__, __le__, __gt__, __ge__
print('Operator overloading cheat sheet loaded!')
Output
Operator overloading cheat sheet loaded!

Practice Exercises

Add Two Points Together
Write Code

Create a Point class with x and y attributes. Add __add__ so that adding two points creates a new point with summed coordinates. Add __repr__ that returns 'Point(<x>, <y>)'. Create Point(1, 2) and Point(3, 4), add them together, and print the result.

# Create the Point class with __add__ and __repr__
Scale a Vector with Multiplication
Write Code

Create a Vector class with x and y. Add __mul__ so vector * number scales both components. Add __rmul__ so number * vector also works. Add __repr__ returning 'Vector(<x>, <y>)'. Print Vector(3, 4) * 2 and 3 * Vector(1, 5).

# Create the Vector class with __mul__ and __rmul__
Fix the Broken __iadd__
Fix the Bug

This Score class uses __iadd__ but the variable becomes None after +=. Find and fix the bug.

class Score:
def __init__(self, points=0):
self.points = points
def __iadd__(self, value):
self.points += value
# Bug: something is missing!
def __repr__(self):
return f'Score({self.points})'
s = Score(10)
s += 5
print(s)
Predict the Operator Output
Predict Output

Read the code carefully and predict exactly what gets printed. Think about which magic methods are called for each operation.

class Num:
def __init__(self, val):
self.val = val
def __add__(self, other):
return Num(self.val + other.val)
def __eq__(self, other):
return self.val == other.val
def __repr__(self):
return str(self.val)
a = Num(10)
b = Num(20)
c = a + b
print(c)
print(a + b == Num(30))
print(a + b == Num(99))
Build a Fraction Class
Write Code

Create a Fraction class with num (numerator) and den (denominator). Add __add__ that adds two fractions using the formula (a/b + c/d = (a*d + c*b) / (b*d)). Add __eq__ that checks if two fractions are equal by cross-multiplying (a/b == c/d when a*d == b*c). Add __repr__ returning '<num>/<den>'. Create Fraction(1, 2) and Fraction(1, 3), add them, and print the result. Then print whether Fraction(1, 2) == Fraction(2, 4).

# Create the Fraction class with __add__, __eq__, and __repr__
Refactor Methods to Operators
Refactor

Refactor this Wallet class to use operator overloading. Replace add_money(amount) with __iadd__, subtract_money(amount) with __isub__, and equals(other) with __eq__. Add __repr__ returning 'Wallet(<balance>)'. Then create Wallet(100), add 50, subtract 30, print the wallet, and print whether it equals Wallet(120).

class Wallet:
def __init__(self, balance=0):
self.balance = balance
def add_money(self, amount):
self.balance += amount
def subtract_money(self, amount):
self.balance -= amount
def equals(self, other):
return self.balance == other.balance
# Refactor the class above, then test it

Harder problems

More problems on this topic: Classes

Related Tutorials

Was this tutorial helpful?