-3

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

Artier
  • 1,648
  • 2
  • 8
  • 22

3 Answers3

3

__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
todel23
  • 128
  • 7
  • I want in the end it should return integer – Artier Aug 14 '22 at 11:03
  • 2
    Then it doesn't satisfy one of the essential properties of an addition, which is that the sum of two objects of the same type is also an object of the same type. You might want to add your objects as suggested here, and use some method/property to get the integer value from the sum. – Thierry Lathuille Aug 14 '22 at 11:12
  • To answer the OP's question on the now deleted answer: the sum you want is now `(aa+bb+cc).val`, which is coherent with the way you get `val` for a single instance. – Thierry Lathuille Aug 14 '22 at 16:49
0

Here's an example of how __add__ and __radd__ should be implemented.

We have a class A that has an attribute n which is an integer. We want to be able to add classes of the same type and we also want to be able to add integer values. Therefore:

class A:
    def __init__(self, n):
        self._n = n
    @property
    def n(self):
        return self._n
    def __add__ (self, other):
        if isinstance(other, int):
            return A(self.n + other)
        assert isinstance(other, type(self))
        return A(self.n + other.n)
    def __radd__(self, other):
        assert isinstance(other, int)
        return A(self.n + other)
    def __str__(self):
        return f'{self.n}'
    def __repr__(self):
        return f'{self.n=}'

a = A(1)
b = A(2)
c = A(3)

print(10+a+10+b+10+c+10)

c += 5
print(c)
print(c.n)

Output:

46
8
8
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

This is what I looking for

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

Out put

44

Artier
  • 1,648
  • 2
  • 8
  • 22