-1
class A:
    x=1
    def __add__(self, obj):
        if isinstance(obj,A):
            return self.x+obj.x
        return "False"

class B(A):
    x=2

a=A()
b=B()
print(a+b)
John Anderson
  • 35,991
  • 4
  • 13
  • 36

1 Answers1

0

The add method takes self, the first object in the addition, and another one, other.

For example:

class A:
    def __init__(self, x):
        self.x=x
    def __add__(self, obj):
        if isinstance(obj,A):
            return self.x+obj.x
        raise NotImplementedError

a = A(3)
b = A(4)
res = a + b  # this is essentially a.__add__(obj=b) 
             # self is implicitly the object a
# res == 7
Charles
  • 3,116
  • 2
  • 11
  • 20
  • how does if isinstance condition gets satisfied as obj is instance of Class B? – Vedant Bhosale Feb 08 '19 at 04:10
  • 2
    Well since B is a subclass of A, `isinstance` will still return `True`. Take a look at [this great SO post](https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance) – Charles Feb 08 '19 at 04:15