Python行为x + y与y + x中的加法重载 [英] Addition overloading in Python behaviour x+y vs y+x
本文介绍了Python行为x + y与y + x中的加法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果有的话,在Python中
In Python if I have
class Foo:
def __add__(self, other):
return 123
然后我可以执行Foo()+1
并获得123.
then I can do Foo()+1
and get 123.
但是,如果我执行1+Foo()
,则会出现异常,因为int不知道如何添加Foos.
But if I do 1+Foo()
I get an exception because int doesn't know how to add Foos.
是否有一种解决方法,以便1 + Foo()也可以工作?
Is there a workaround so that 1+Foo() works too?
推荐答案
实施 查看全文