Concatenate two strings using Operator Overloading in Python

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# taking two numbers
a = 2
b = 3
  
# using '+' operator add them
c = a+b
  
# printing the result
print("The sum of these two numbers is ", c)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# taking two strings from the user
a = 'abc'
b = 'def'
  
# using '+' operator concatenate them
c = a+b
  
# printing the result
print("After Concatenation the string becomes", c)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# let us define a class with add method
class operatoroverloading:
    
    def add(self, a, b):
        self.c = a+b
        return self.c
  
  
# creating an object of class
obj = operatoroverloading()
  
# using add method by passing integers
# as argument
result = obj.add(23, 9)
print("sum is", result)
  
# using same add method by passing strings
# as argument
result = obj.add("23", "9")
print("Concatenated string is", result)

chevron_right


Output:

sum is 32
Concatenated string is 239



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.