Reputation: 5698
I know I can do simple operator overloading in python by the following way.
Let say overloading '+' operator.
class A(object):
def __init__(self,value):
self.value = value
def __add__(self,other):
return self.value + other.value
a1 = A(10)
a2 = A(20)
print a1 + a2
But It fails when I try to do the following,
a1 = A(10)
a2 = A(20)
a3 = A(30)
print a1 + a2 + a3
Since the __add__
accepts only 2 parameters. What is the best solution to achieve operator overloading with n number of operands.
Upvotes: 1
Views: 1843
Reputation: 160427
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
Upvotes: 4
Reputation: 1450
The problem is that
a1 + a2 + a3
gives
30 + a3
30 is an int, and ints do not know how to sum to A
You should return an instance of A in your __add__
function
Upvotes: 0