In this tutorial you will learn:

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.

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.

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:

`class Distance:  def __init__(self, feet, inches):    self.feet = feet    self.inches = inches  def __add__(self, dist):    d = self.feet + dist.feet    i = self.inches + dist.inches    return Distance(d,i)`

Let's override subtraction operator and add the code in the same class.

`  def __sub__(self, dist):    d = self.feet - dist.feet    i = self.inches - dist.inches    return Distance(d,i)`

After subtraction lets override multiplication operator as well.

`def __mul__(self, dist):    d = self.feet * dist.feet    i = self.inches * dist.inches    return Distance(d,i)`

Now override the print function so it can print the result.

`def __str__(self):  	return "Feet, Inches {0},{1}".format(self.feet,self.inches)`

Now let's try to use the newly overridden operators.
`print("\n\n** Adding Objects **")dist1 = Distance(2, 3)dist2 = Distance(5, 6)result = dist1 + dist2print(result) print("\n\n** Subtracting Objects **")dist1 = Distance(10, 7)dist2 = Distance(4, 6)result = dist1 - dist2print(result) print("\n\n** Multiplying Objects **")dist1 = Distance(8, 3)dist2 = Distance(2, 2)result = dist1 * dist2print(result)`

### Tags

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.