Python operator overloading with multiple operands
<p>I know I can do simple operator overloading in python by the following way.</p>

<p>Let say overloading '+' operator.</p>

<pre><code>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
</code></pre>

<p>But It fails when I try to do the following,</p>

<pre><code>a1 = A(10)
a2 = A(20)
a3 = A(30)
print a1 + a2 + a3
</code></pre>

<p>Since the <code>__add__</code> accepts only 2 parameters. What is the best solution to achieve operator overloading with n number of operands.</p>

<p>This is failing because <code>a1 + a2</code> return an <code>int</code> instance and its <code>__add__</code> is called which doesn't support addition with the custom class <code>A</code>; you could return a <code>A</code> instance in <code>__add__</code> to eliminate the Exception for this specific operation:</p>

<pre><code>class A(object):
  def __init__(self,value):
    self.value = value

  def __add__(self,other):
    return type(self)(self.value + other.value)
</code></pre>

<p>Adding them together now behaves in the expected way:</p>

<pre><code>&gt;&gt;&gt; a1 = A(10)
&gt;&gt;&gt; a2 = A(20)
&gt;&gt;&gt; a3 = A(30)
&gt;&gt;&gt; print(a1 + a2 + a3)
&lt;__main__.A object at 0x7f2acd7d25c0&gt;
&gt;&gt;&gt; print((a1 + a2 + a3).value)
60
</code></pre>

<p>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.</p>

<p>If you want a nice result displayed when you <code>print</code> these objects, you should also implement <code>__str__</code> to return the value when called:</p>

<pre><code>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)
</code></pre>

<p>Now printing has the effect you need:</p>

<pre><code>&gt;&gt;&gt; print(a1 + a2 + a3)
60
</code></pre>

python python-2.7 python-3.x python-2.x