user3074414
user3074414

Reputation: 83

Addition overloading in Python behaviour x+y vs y+x

In Python if I have

class Foo:
  def __add__(self, other):
    return 123

then I can do Foo()+1 and get 123.

But if I do 1+Foo() I get an exception because int doesn't know how to add Foos.

Is there a workaround so that 1+Foo() works too?

Upvotes: 0

Views: 47

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799190

Implement the __radd__() method as well.

Upvotes: 3

Related Questions