Search code examples
pythonobjectintegeradditionbuilt-in

add more than two objects with __add__ function


I have a class it can successfully add two variables of object of class a

class a():
    def __add__(self, other):
        return self.val+other.val
    def __init__(self,a):
        self.val=a
aa=a(22)
bb=a(11)
aa+bb
33

But when I try to give it third object to add, it through error

cc=a(11)
aa+bb+cc
Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    aa+bb+cc
TypeError: unsupported operand type(s) for +: 'int' and 'a'

It is because first two aa+bb return int and its add function is design to add object addition Any one can suggest how I can add three objects

I find this link Using __add__ operator with multiple arguments in Python but it is working on one object and 2 integers. But I want to add three objects. and all these three combine and return integer


Solution

  • __add__ must return an instance of a class, not int

    class a():
        def __add__(self, other):
            return a(self.val + other.val)
        def __init__(self, a):
            self.val = a