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.- 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)
- def __sub__(self, dist):
- d = self.feet - dist.feet
- i = self.inches - dist.inches
- return Distance(d,i)
- def __mul__(self, dist):
- d = self.feet * dist.feet
- i = self.inches * dist.inches
- return Distance(d,i)
- def __str__(self):
- return "Feet, Inches {0},{1}".format(self.feet,self.inches)
- print("\n\n** Adding Objects **")
- dist1 = Distance(2, 3)
- dist2 = Distance(5, 6)
- result = dist1 + dist2
- print(result)
- print("\n\n** Subtracting Objects **")
- dist1 = Distance(10, 7)
- dist2 = Distance(4, 6)
- result = dist1 - dist2
- print(result)
- print("\n\n** Multiplying Objects **")
- dist1 = Distance(8, 3)
- dist2 = Distance(2, 2)
- result = dist1 * dist2
- print(result)
Add new comment
- 197 views