5

HI

Trying to understand how __radd__ works. I have the code

>>> class X(object):
    def __init__(self, x):
        self.x = x
    def __radd__(self, other):
        return X(self.x + other.x)


>>> a = X(5)
>>> b = X(10)
>>> a + b

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    a + b
TypeError: unsupported operand type(s) for +: 'X' and 'X'
>>> b + a

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    b + a
TypeError: unsupported operand type(s) for +: 'X' and 'X'

Why is this not working? What am I doing wrong here?

3

4 Answers 4

11

Python docs for operators

"These functions are only called if the left operand does not support the corresponding operation and the operands are of different types."

See also Footnote 2

Since the operands are of the same type, you need to define __add__.

0
6

These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.

I am using Python3 so please ignore the grammatical differences:

>>> class X:
    def __init__(self,v):
        self.v=v
    def __radd__(self,other):
        return X(self.v+other.v)
>>> class Y:
    def __init__(self,v):
    self.v=v

>>> x=X(2)
>>> y=Y(3)
>>> x+y
Traceback (most recent call last):
  File "<pyshell#120>", line 1, in <module>
    x+y
TypeError: unsupported operand type(s) for +: 'X' and 'Y'
>>> y+x
<__main__.X object at 0x020AD3B0>
>>> z=y+x
>>> z.v
5
0

These functions are only called if the left operand does not support the corresponding operation and the operands are of different types. For example,

class X:
  def __init__(self, num):
    self.num = num

class Y:
  def __init__(self, num):
    self.num = num

  def __radd__(self, other_obj):
    return Y(self.num+other_obj.num)

  def __str__(self):
    return str(self.num)

>>> x = X(2)
>>> y = Y(3)
>>> print(x+y)
5
>>>
>>> print(y+x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-60-9d7469decd6e> in <module>()
----> 1 print(y+x)

TypeError: unsupported operand type(s) for +: 'Y' and 'X'
-1

Try this

class X(object):

 def __init__(self, x):

     self.x = x

 def __radd__(self, other):

     return self.x + other

a = X(5)

b = X(10)

print sum([a,b])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.