Tim Tim - 5 months ago 11
Python Question

Why is __radd__ not working

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?

Answer

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__.