Editor

Python Program to Show Operator Overloading

Intermediate · Classes and objects

Operator overloading means giving operators such as +, - and == a meaning for objects of your own class. Python does this through special methods, also called magic or dunder methods, whose names start and end with two underscores. This program makes a Vector class whose objects can be added, subtracted, multiplied, compared and printed.

Program

operator_overloading.py
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other): # v1 + v2
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other): # v1 - v2
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, number): # v * 3
return Vector(self.x * number, self.y * number)
def __eq__(self, other): # v1 == v2
return self.x == other.x and self.y == other.y
def __str__(self): # print(v)
return f"Vector({self.x}, {self.y})"
a = Vector(2, 3)
b = Vector(5, 1)
print("a =", a)
print("b =", b)
print("a + b =", a + b)
print("a - b =", a - b)
print("a * 3 =", a * 3)
print("a == Vector(2, 3):", a == Vector(2, 3))
Output
a = Vector(2, 3)
b = Vector(5, 1)
a + b = Vector(7, 4)
a - b = Vector(-3, 2)
a * 3 = Vector(6, 9)
a == Vector(2, 3): True

How it works

  1. When Python sees a + b with two objects, it calls a.__add__(b), so defining __add__ decides what + does for vectors.
  2. __add__, __sub__ and __mul__ each return a new Vector, so a and b stay unchanged.
  3. __eq__ makes == compare the coordinates; without it, two separate objects with the same values would not count as equal.
  4. __str__ sets what print() shows, here Vector(7, 4) instead of an unreadable memory address.
  5. a * 3 works, but 3 * a raises an error unless the class also defines __rmul__, the method for a number on the left.

Other ways to write it

Overloading < to sort objects

Overloading < to sort objects
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __lt__(self, other): # s1 < s2 compares marks
return self.marks < other.marks
def __repr__(self):
return f"{self.name}({self.marks})"
students = [Student("Aarav", 82), Student("Diya", 95), Student("Kabir", 71)]
print("Sorted by marks:", sorted(students))
print("Highest:", max(students))
print("Is Diya below Aarav?", students[1] < students[0])
Output
Sorted by marks: [Kabir(71), Aarav(82), Diya(95)]
Highest: Diya(95)
Is Diya below Aarav? False

Defining __lt__ (less than) is enough for sorted(), min() and max() to work on your objects, and __repr__ is what Python shows for objects inside a list.

Adding durations

Adding durations
class Duration:
def __init__(self, hours, minutes):
self.hours = hours + minutes // 60 # carry whole hours over
self.minutes = minutes % 60
def __add__(self, other):
return Duration(self.hours + other.hours, self.minutes + other.minutes)
def __str__(self):
return f"{self.hours} h {self.minutes} min"
movie = Duration(2, 35)
ads = Duration(0, 40)
print("Movie:", movie)
print("Ads:", ads)
print("Total:", movie + ads)
Output
Movie: 2 h 35 min
Ads: 0 h 40 min
Total: 3 h 15 min

__add__ adds the hours and minutes, and the constructor carries every 60 minutes over into an hour, so 2 h 35 min + 40 min gives 3 h 15 min.

Try it yourself

Add a __neg__ method so that -a gives Vector(-2, -3).

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises