Operator Overloading refers to using the same operator to perform different tasks by passing different types of data as arguments. To understand how ‘+’ operator works in two different ways in python let us take the following example
Python3
a = 2
b = 3
c = a + b
print ( "The sum of these two numbers is " , c)
|
Output:
The sum of these two numbers is 5
In this example we used ‘+’ operator to add numbers, now let us take one more example to understand how ‘+’ operator is used to concatenate strings.
Python3
a = 'abc'
b = 'def'
c = a + b
print ( "After Concatenation the string becomes" , c)
|
Output:
After Concatenation the string becomes abcdef
For a better understanding of operator overloading, here is an example where a common method is used for both purposes.
Python3
class operatoroverloading:
def add( self , a, b):
self .c = a + b
return self .c
obj = operatoroverloading()
result = obj.add( 23 , 9 )
print ( "sum is" , result)
result = obj.add( "23" , "9" )
print ( "Concatenated string is" , result)
|
Output:
sum is 32
Concatenated string is 239
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 Jul, 2020
Like Article
Save Article