3

在 Python 中,您可以通过定义__add__. 这将使添加具有其他值/实例的类实例成为可能,但您不能将内置函数添加到实例中:

foo = Foo()
bar = foo + 6 # Works
bar = 6 + foo # TypeError: unsupported operand type(s) for +: 'int' and 'Foo'

有什么办法可以启用它吗?

4

2 回答 2

6

当您的实例位于右侧时,您必须定义__radd__(self, other)覆盖运算符的方法。+

于 2012-10-20T17:35:08.320 回答
4

You cannot override the + operator for integers. What you should do is to override the __radd__(self, other) function in the Foo class only. The self variable references a Foo instance, not an integer, and the other variable references the object on the left side of the + operator. When bar = 6 + foo is evaluated, the attempt to evaluate 6.__add__(foo) fails and then Python tries foo.__radd__(6) (reverse __add__). If you override __radd__ inside Foo, the reverse __add__ succeeds, and the evaluation of 6 + foo is the result of foo.__radd__(6).

def __radd__(self, other):
   return self + other
于 2012-10-20T17:48:58.027 回答