A complete Guide on Operator Overloading in Python

In this Python article, we will explore one of the important topics of python, we will discuss operator overloading. How does operator overloading works and how to extend the existing functionality? This is also an important topic in many interviews. Let’s begin.


1. What is operator overloading?

In our previous article, we discussed polymorphism via Inheritence. Operator overloading is a section that comes under the compile-time polymorphism.

Read More about Python Operators

When we use the same operator to perform different tasks in different scenarios it is known as Operator Overloading.

For example, the operator ‘+’ can be used not only to concatenate two strings but also to add two numbers and merge two lists.

So we are using a single operator but it works differently when used with different data types. How does that happen? It happens because ‘+’ operator is overloaded by int, list, str class, etc and they have modified the implementation as per the requirements of that particular type.

1.1. How does Opeerator Overloading works?

Suppose, we have defined a class with the name ‘Oscar‘ and we have created two instances(objects) with names ‘o1’ and ‘o2’.

If we now try to add these two objects ‘o1‘ and ‘o2‘ with the help of the binary ‘+’ operator, then definitely it will throw an error. This error occurs because there is no in-built function that will help the compiler to add these two objects.

In order to enable such an operation, we will define a method for “+” operator via the process of operator overloading.

NOTE: Python allows us to overload all existing operators but it does not allow the creation of a new operator.

1.2. Overloading the addition operator(+)

There are some special functions or it can be mentioned as some ‘magic function‘ that can be used for operator overloading. Such functions are invoked automatically as soon as they get associated with any specific operator.

For example, when we use + operator, the magic method __add__ is invoked in which the behavior for + operator is defined.

class OperatorOverloadTest:
  def __init__(self, code):
    self.code = code

  def __add__(self, obj):
    """add two objects"""
    return self.code + obj.code


inst1 = OperatorOverloadTest(2)
inst2 = OperatorOverloadTest(4)

inst4 = OperatorOverloadTest("codingeek")
inst5 = OperatorOverloadTest(".com")

print(inst1 + inst2)
print(inst4 + inst5)
Output
6
codingeek.com

Here, in the above example, the instance object 1(inst1) and instance object 2(inst2) are added together using the __add__ function.

Let’s take one more example. In this example, we will have two values associated with an object and when we do the addition, only the corresponding values are added together.

# + operator overloading.

class AddTuples:
  def __init__(self, val1, val2):
    self.val1 = val1
    self.val2 = val2

  def __add__(self, additional):
    """adding two objects"""
    return self.val1 + additional.val1, self.val2 + additional.val2


add1 = AddTuples(3, 7)
add2 = AddTuples(9, 1)
add3 = add1 + add2
print(add3)
Output
(12, 8)

1.3. Overloading the Comparison Operator (>, <, =)

Let’s overload greater than ( > ) operator with a small example.

class GreaterThanOperatorOverload:
  def __init__(self, val):
    self.val = val

  def __gt__(self, extra):
    if(self.val > extra.val):
      return True
    else:
      return False


c1 = GreaterThanOperatorOverload(3)
c2 = GreaterThanOperatorOverload(7)
print(f"c1 > c2 => {c1 > c2}")
print(f"c2 > c1 => {c2 > c1}")
Output
c1 > c2 => False
c2 > c1 => True

Let’s overload the lesser than ( < ) and equal ( == ) operator with a small example.

class OperatorOverloadTest:

  def __init__(self, val):
    self.val = val

  def __lt__(self, additional):
    return True if self.val < additional.val else False

  def __eq__(self, additional):
    return True if self.val == additional.val else False


r1 = OperatorOverloadTest(3)
r2 = OperatorOverloadTest(9)
r3 = OperatorOverloadTest(4)
r4 = OperatorOverloadTest(4)
print(f"Is r1 < r2 => {r1 < r2}")
print(f"Is r1 < r3 => {r1 < r3}")
print(f"Is r1 < r4 => {r1 < r4}")
print(f"Is r1 == r4 => {r1 == r4}")
print(f"Is r2 == r4 => {r2 == r4}")
print(f"Is r3 == r4 => {r3 == r4}")
print(f"Is r3 == r1 => {r3 == r1}")
Output
Is r1 < r2 => True
Is r1 < r3 => True
Is r1 < r4 => True
Is r1 == r4 => False
Is r2 == r4 => False
Is r3 == r4 => True
Is r3 == r1 => False

2. What are Special functions in Python?

In python, if we declare any function inside the class with a double underscore “__” then it is known as a special function.

Read More about Functions in Python

Such functions are not typical in nature like that we define for a class. The __init__() function is a special function, which is called whenever we try to create a new object of that class.

Special functions help in making the declared class compatible with built-in functions.

We have various other special functions. Click here to visit the official documentation.

Some of the special functions are also magic functions which are listed below, these magic functions are used for operator overloading

3. Python Magic methods for Operator Overloading

Different operators can be overloaded using their specific magic method. Here is the list of all of the used magic methods.

We can override these functions following the examples above and implement the required functionality for any of them. Try obverloading some operator and share your code in the comments.

3.1. Binary Operators

OperatorMagic Method
+__add__(self, otherobject)
__sub__(self, otherobject)
*__mul__(self, otherobject)
/__truediv__(self, otherobject)
//__floordiv__(self, otherobject)
%__mod__(self, otherobject)
**__pow__(self, otherobject)
>>__rshift__(self, otherobject)
<<__lshift__(self, otherobject)
&__and__(self, otherobject)
|__or__(self, otherobject)
^__xor__(self, otherobject)
List for Binary operators

3.2. Comparison Operators

OperatorMagic Method
<__lt__(self, otherobject)
>__gt__(self, otherobject)
<=__le__(self, otherobject)
>=__ge__(self, otherobject)
==__eq__(self, otherobject)
!=__ne__(self, otherobject)
List for Comparison operators

3.3. Assignment Operators

OperatorMagic Method
-=__isub__(self, otherobject)
+=__iadd__(self, otherobject)
*=__imul__(self, otherobject)
/=__idiv__(self, otherobject)
//=__ifloordiv__(self, otherobject)
%=__imod__(self, otherobject)
**=__ipow__(self, otherobject)
>>=__irshift__(self, otherobject)
<<=__ilshift__(self, otherobject)
&=__iand__(self, otherobject)
|=__ior__(self, otherobject)
^=__ixor__(self, otherobject)
List for Assignment operatos

3.4. Unary Operators

__neg__(self, otherobject)
+__pos__(self, otherobject)
~__invert__(self, otherobject)
List for Unary operators

4. Conclusion

Finally, let’s sum up everything. In this article, we discussed about the operator overlaoding in python.

  • What is operator overloading and how does it works?
  • Overloading the addition operator(+), Overloading the comparison operator(>, <, =)
  • What are Special functions in Python, why do we use them?
  • List of all the python magic method for operator overloading

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index