Python Operator Overloading

In this tutorial you will learn:

  • Operator Overloading
  • Operator Overloading in Python
  • Overloading Addition Operator
  • Overloading Subtraction Operator
  • Overloading Multiplication Operator

Operator Overloading

Sometimes we want to modify the functionality of the common operators such as ‘+, -, * and /‘ and we can do that through a concept known as Operator Overloading. So Operator Overloading allows us to extend the functionality of that operator.

Operator Overloading in Python

Like other Object Oriented Programming languages Python also offers the functionality of Overloading Operators. If we take the example of string object then using the + operator appends the two strings together but if we take the example of float or integers then using + operator between two numbers would add those two numbers together. So we can say that the + operator is overloaded for string objects instead of adding their ASCII characters it appends the two strings. Now we use Operator Overloading when we want to extend its functionality to work with our custom classes.

Overloading Subtraction and Addition Operators

When we create our custom classes and try to add the two objects together we cannot get the desired results until we overload the operators to work with our custom class.

Example:

Let's create a distance class and add override addition operator.
  1. class Distance:
  2. def __init__(self, feet, inches):
  3. self.feet = feet
  4. self.inches = inches
  5. def __add__(self, dist):
  6. d = self.feet + dist.feet
  7. i = self.inches + dist.inches
  8. return Distance(d,i)
Let's override subtraction operator and add the code in the same class.
  1. def __sub__(self, dist):
  2. d = self.feet - dist.feet
  3. i = self.inches - dist.inches
  4. return Distance(d,i)
After subtraction lets override multiplication operator as well.
  1. def __mul__(self, dist):
  2. d = self.feet * dist.feet
  3. i = self.inches * dist.inches
  4. return Distance(d,i)
Now override the print function so it can print the result.
  1. def __str__(self):
  2. return "Feet, Inches {0},{1}".format(self.feet,self.inches)
Now let's try to use the newly overridden operators.
  1. print("\n\n** Adding Objects **")
  2. dist1 = Distance(2, 3)
  3. dist2 = Distance(5, 6)
  4. result = dist1 + dist2
  5. print(result)
  6.  
  7. print("\n\n** Subtracting Objects **")
  8. dist1 = Distance(10, 7)
  9. dist2 = Distance(4, 6)
  10. result = dist1 - dist2
  11. print(result)
  12.  
  13. print("\n\n** Multiplying Objects **")
  14. dist1 = Distance(8, 3)
  15. dist2 = Distance(2, 2)
  16. result = dist1 * dist2
  17. print(result)

Add new comment