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
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
- When Python sees
a + bwith two objects, it callsa.__add__(b), so defining__add__decides what + does for vectors. __add__,__sub__and__mul__each return a newVector, soaandbstay unchanged.__eq__makes==compare the coordinates; without it, two separate objects with the same values would not count as equal.__str__sets whatprint()shows, hereVector(7, 4)instead of an unreadable memory address.a * 3works, but3 * araises 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
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises