__add__()

Let's add two variables, x and y:

 x = 2
 y = 3
 x + y
 5

When Python executed this code, it called the __add__ method on x, passing it y:

>>> x.__add__(y)
5

The add method is called when using the + operator. We can define a custom add method for our class.

p1 + p2 is equal to p1._add__(p2)

class Person:
    def __init__(self, name, age):
      self.name = name
      self.age = age
    def __add__(self,other)  :
      age = self.age+other.age
      return age


person1 = Person('olee',25)      
person2 = Person('mim',18)   

print(person1+person2)

OutPut

43

Last updated