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

青春壹個敷衍的年華 提交于 2019-12-31 06:27:12

问题


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.



来源:https://stackoverflow.com/questions/20832112/addition-overloading-in-python-behaviour-xy-vs-yx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!