Python __add__() magic method
Last Updated :
04 Sep, 2022
Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator “+” in Python.
Python __add__() Syntax
Syntax: obj1.__add__(self, obj2)
- obj1: First object to add in the second object.
- obj2: Second object to add in the first object.
Returns: Returns a new object representing the summation of the other two objects.
Python __add__() magic method Example
Python __add__() method adds two objects and returns a new object as a resultant object in Python. The below example returns a new object,
Python3
class GFG:
def __init__( self , val):
self .val = val
def __add__( self , val2):
return GFG( self .val + val2.val)
obj1 = GFG( "Geeks" )
obj2 = GFG( "ForGeeks" )
obj3 = obj1 + obj2
print (obj3.val)
|
Output:
GeeksForGeeks
Note: If we had not defined the __add__() method, Python would have raised a TypeError.
Python3
class GFG:
def __init__( self , val):
self .val = val
obj1 = GFG( "Geeks" )
obj2 = GFG( "ForGeeks" )
obj3 = obj1 + obj2
print (obj3.val)
|
Output:
Traceback (most recent call last):
File "/home/d8b3b04f2954b8c46b64bc7dd37f6aa4.py", line 11, in <module>
obj3 = obj1 + obj2
TypeError: unsupported operand type(s) for +: 'GFG' and 'GFG'