Addition overloading in Python behaviour x+y vs y+

2019-03-04 01:03发布

问题:

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?

回答1:

Implement the __radd__() method as well.