Hello folks....!!!!
Today let us look at the concepts of operator overloading in
python.
Operator overloading
The concept of overloading helps to make an operator perform different
actions on different parameters. For example we could have come across
overloading of '+' in C-programming. If the parameters passed are of
numerals, their sum would be returned, if string concatenation of the
parameters would be returned.
Similarly in python we can overload an operator by
writing special functions. Special functions are written by placing double
underscores without a space (__) before and after the function name. Look at
the table below to know the appropriate special function:
*True division - returns a floating point value for integers also.
Now let us look at an example :
Assume that we have two quadratic equations as given below, When we sum up these two we get the answer below,
So we need to add the coefficients appropriately. To do this we can use
operator overloading method.
|
The code snippet above can be used for overloading '+' operator. The operator is made to add appropriate coefficients. I have
written a code for taking only the coefficients of x^2, x, constant term. Here, the __init__() initializes the coefficients for each term when an instance of the
class 'quadratic' is created.
The
__add__(self,a) is the
special function. While writing eq1+eq2 in the parameters passed to the
special function, eq1 corresponds to the self and eq2 corresponds to a.
The function have to return multiple values and thus they are placed
inside a list and then returned.
In the similar way we can overload any other arithmetic operator by
writing special functions.
Now consider overloading the relational operators (<, <=, >,
>=, ==)
Consider the input as distance metrics feet and inches. For example
: 5 feet 4 inches
Now let us get two user inputs like the one given above and compare them.
Let us make it print which is the greater one.
Here we can also overload the print() function. Look at the code
below
class distance:
def __init__(self):
self.inch=0
self.feet=0
def get_input(self):
self.feet=int(input("Enter feet :"))
self.inch=int(input("Enter inches
:"))
def __gt__(self,a):
if self.inch>a.inch and self.feet>a.feet:
print(self)
else:
print(a)
def __str__(self):
return str(self.feet)+" feet
"+str(self.inch)+" inches is greater"
d1=distance()
d2=distance()
d1.get_input()
d2.get_input()
d1>d2
Here the '>' operator is overloaded. The function __ge__(self,a) is a special function. If you write d1>d2, d1 corresponds to self
and d2 corresponds to a. You can write any name instead of self and a.
The print() has also been overloaded using __str__(self). You can format the output using this. Now in this code I want to
print which input is greater whenever print() is called. So the string
to printed is formed and returned.
Thus the output got is
Now try your own ideas on operator overloading.
Next Topic👉
Comments
Post a Comment