This is failing because a1 + a2
return an int
instance and its __add__
is called which doesn't support addition with the custom class A
; you could return a A
instance in __add__
to eliminate the Exception for this specific operation:
class A(object):
def __init__(self,value):
self.value = value
def __add__(self,other):
return type(self)(self.value + other.value)
Adding them together now behaves in the expected way:
>>> a1 = A(10)
>>> a2 = A(20)
>>> a3 = A(30)
>>> print(a1 + a2 + a3)
<__main__.A object at 0x7f2acd7d25c0>
>>> print((a1 + a2 + a3).value)
60
This class of course suffers from the same issues with other operations; you need to implement the other dunders to return an instance of your class or else you'll bump into the same result with other operations.
If you want a nice result displayed when you print
these objects, you should also implement __str__
to return the value when called:
class A(object):
def __init__(self,value):
self.value = value
def __add__(self,other):
return A(self.value + other.value)
def __str__(self):
return "{}".format(self.value)
Now printing has the effect you need:
>>> print(a1 + a2 + a3)
60