1

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.

0

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

4 Comments

Why temporarily? Looks like the proper solution to me.
temporarily might be a wrong word, point is this fixes the issue for the specific operation but in general you'll get weird results if you don't implement all required operations.
Thanks.But I wanted to have the result by just giving a1 + a2 + a3 ,not using the value attribute externally.
Then you overload __str__ (and maybe __repr__) @karthi_ms to return the result :-)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.