Course contentsShow
← Python
Lesson 448 of 1,0607. Object-Oriented ProgrammingFree lesson

Implementing Arithmetic Operator Overloading

Use magic methods like __add__, __sub__, and __mul__ to enable standard mathematical operations on your custom objects.

In this lesson, you will learn how to make your custom objects behave like built-in numbers by using magic methods to define how standard operators like +, -, and * should function.

Making Objects "Do Math"

By default, Python doesn't know how to "add" two custom objects together. If you try to use + on instances of a class you wrote, Python will raise a TypeError. You can resolve this by implementing "magic methods" (also called dunder methods) inside your class. These methods are automatically triggered when the corresponding operator is used.

The Magic Methods

To enable arithmetic, you define specific methods:

  • __add__(self, other): Invoked by the + operator.
  • __sub__(self, other): Invoked by the - operator.
  • __mul__(self, other): Invoked by the * operator.

Consider a class representing a Vector:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        # Return a new Vector representing the sum
        return Vector(self.x + other.x, self.y + other.y)

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

v1 = Vector(2, 3)
v2 = Vector(5, 5)

# This triggers v1.__add__(v2)
result = v1 + v2
print(result)  # Output: Vector(7, 8)

How It Works

When you write v1 + v2, Python looks at the left object (v1) and checks if it has an __add__ method. It then passes v2 as the other argument to that method. Inside the method, you define the custom logic for what the addition means for your specific objects—like adding their individual components together.

By returning a new instance of your class from these methods, you allow for "chaining" operations, meaning you can perform v1 + v2 + v3 seamlessly. This makes your custom objects feel like a natural part of the Python language.

Key Takeaway: Arithmetic operator overloading allows you to define custom mathematical behavior for your objects by implementing magic methods like __add__, __sub__, and __mul__.