OneCompiler

Operator overloading in Python

224


In this post, we are going to take a look at operator overloading in Python.

What is Operator overloading?

It means extending the predefined meaning of an operator with a custom definition. For example, we can use the + to add integers or to join strings. But with the help of operator overloading, we can achieve addition between and string & integer.

Overloading the binary + operator

Generally, we use the + operator to add integers or join strings in the below way.

# Addition of integers
print(1+2)

# Joining of strings
print("a" + "b")

But with the help of operator overloading, we can write a custom definition to the +

class A: 
  # constructor
  def __init__ (self,a):
    self.a = a
  # string and integer addition
  def __add__ (self, o):
    print(str(self.a) + o.a)
  
o1 = A(1)
o2 = A("Hello")
o1 + o2

Check Output Here