0
0
Pythonprogramming~5 mins

Arithmetic operator overloading in Python

Choose your learning style9 modes available
Introduction
Arithmetic operator overloading lets you change how operators like +, -, * work for your own objects. It helps your objects behave like numbers or other built-in types.
You want to add two custom objects and get a meaningful result.
You want to multiply objects in a way that fits your program's logic.
You want to compare or combine objects using arithmetic symbols.
You want your objects to work naturally with math operators in expressions.
Syntax
Python
class ClassName:
    def __add__(self, other):
        # code to add self and other
        return result

    def __sub__(self, other):
        # code to subtract other from self
        return result

    def __mul__(self, other):
        # code to multiply self and other
        return result
Use special method names like __add__, __sub__, __mul__ to overload +, -, * respectively.
The method takes another object as input and returns the result of the operation.
Examples
This class adds two Number objects by adding their values.
Python
class Number:
    def __init__(self, value):
        self.value = value
    def __add__(self, other):
        return Number(self.value + other.value)
    def __str__(self):
        return str(self.value)
Adding two Number objects calls __add__ and prints the sum.
Python
a = Number(5)
b = Number(3)
c = a + b
print(c)
This Vector class multiplies by a number (scalar) using * operator.
Python
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)
    def __str__(self):
        return f"({self.x}, {self.y})"
Sample Program
This program creates two Number objects and uses +, -, * operators. Each operator calls the matching method to do the math and returns a new Number object.
Python
class Number:
    def __init__(self, value):
        self.value = value
    def __add__(self, other):
        return Number(self.value + other.value)
    def __sub__(self, other):
        return Number(self.value - other.value)
    def __mul__(self, other):
        return Number(self.value * other.value)
    def __str__(self):
        return str(self.value)

num1 = Number(10)
num2 = Number(4)

print(num1 + num2)  # 14
print(num1 - num2)  # 6
print(num1 * num2)  # 40
OutputSuccess
Important Notes
Operator overloading makes your objects easier to use and read in math expressions.
Always return a new object or a value that makes sense for the operation.
If you don't overload an operator, Python uses default behavior or errors if unsupported.
Summary
Arithmetic operator overloading lets you define how +, -, * work for your objects.
Use special methods like __add__, __sub__, __mul__ inside your class.
It helps your custom objects behave like numbers in expressions.