How to overload plus operator in python / Operator overloading in python

What is operator overloading?
Overloading an operator means adding it some behavior for your own customized requirements apart from its default operation. Example, + operator is used for adding two numbers, merging lists or concatenating strings but what if you want to add two objects of a class using +.  Consider the below class for understanding the concept better.

class Course:
    def __init__(self, name, hours):
        self.name=name
        self.hours=hours

Above code defines a class Course which has two fields name and hours. Now what if we create its objects and try to add them as shown.

courseOne = Course("python basics", 10)
courseTwo = Course("python advanced", 20)
print("Total duration of both courses =",courseOne+courseTwo, "hours")

By default, if you try to do this, you will get

TypeError: unsupported operand type(s) for +: ‘Course’ and ‘Course’

Adding behavior to + operator(or any built-in python operators) so that it can work on custom objects is called operator overloading.

Overloading requirement
When we try to add our custom objects, python complains by throwing an error because it does not know how to add those objects. In above example, both the two course objects had two fields name and hours. Now how would python know which fields to add when we try to add these objects, that is, whether it should add both fields or only name or hours field. That is why it flags an error.
Thus, for successfully adding our own class objects, we need to tell python how it should perform addition over them. This is done by writing a special function in our class explained in detail below.

+ operator is already overloaded for number, string and list classes since it performs different functions when used to add numbers, string or list together. When used with numbers, it adds their numerical values. When used with strings, it concatenates them and when used with lists, it merges them.

How to overload + operator
Python provides a special function which we can write in our class. This function is called special because it is an inbuilt function and gets called automatically when plus(+) operator is applied to objects of this class. This function has a pre-defined syntax but its implementation is defined by us since we should decide how the objects of our class shall be added.
Name of this function is add prefixed and suffixed with double underscores(__) and it takes 2 arguments which represent the two objects to be added. Thus, the complete name of this function is __add__. It is also called magic function.

class Course:
    def __init__(self, name, hours):
        self.name=name
        self.hours=hours
 
    # overload plus operator for objects of this class
    def __add__(self, other):
        # add hours of both courses and return their sum
        return self.hours + other.hours
 
 
courseOne = Course("python basics", 10)
courseTwo = Course("python advanced", 20)
print("Total duration of both courses =",courseOne + courseTwo, "hours")

Above code when executed will print following output

Total duration of both courses = 30 hours

Look hours of both the objects are successfully added. Thus, we have successfully overloaded plus operator for our custom class objects.
Though the implementation of __add__ function depends on us, it should be done sensibly since it makes sense to add hours of two courses together but it will be absurd if we add their names also, although this is possible.

When we use + operator to add objects of a class, __add__ function is automatically called.

Overloading other operators
Above we saw the method of overloading plus operator for objects of user defined classes by implementing a special method __add__ in the class. Similarly, for other operators also, there are corresponding special functions which should be implemented for overloading them. Below tables summarizes the functions that are required to be implemented for overloading operators.
Mathematical operators

NameSymbolSpecial Function
Addition+__add__(self, other)
Subtraction__sub__(self, other)
Division/__truediv__(self, other)
Floor Division//__floordiv__(self, other)
Modulus(or Remainder)%__mod(self, other)__
Power**__pow(self, other)__
Power**__pow(self, other)__
Power**__pow(self, other)__

Assignment Operators

NameSymbolSpecial Function
Increment+=__iadd__(self, other)
Decrement-=__isub__(self, other)
Product*=__imul__(self, other)
Division/=__idiv(self, other)__
Modulus%=__imod(self, other)__
Power**=__ipow(self, other)__

Relational Operators

NameSymbolSpecial Function
Less than<__lt(self, other)__
Greater than>__gt__(self, other)
Equal to==__eq__(self, other)
Not equal!=__ne__(self, other)
Less than or equal to<=__le__(self, other)
Greater than or equal to>=__gt__(self, other)

Functions to overload relational operators generally return True or False since they are used to compare objects and comparison always returns either of these values.

Hope you liked this post, keep visiting for more.

0

Mark Your Impression

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.