在Python3
的官方文档中,类似__radd__()
这样的“反运算”方法,说到了如下的“被调用”条件:
These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.
翻译:这些函数只有在
1. 左操作数不支持相关运算 并且
2. 两个操作数是不同类型时
才被调用。
现有如下代码:
>>> class Nint(int):
def __radd__(self, other):
return int.__sub__(other, self)
>>> a = Nint(5)
>>> b = Nint(3)
>>> a + b
8
>>> 1 + b
-2
关于a+b=8
这个我清楚,因为Nint继承了int的__add__
方法。
但是为什么1+b
会调用b对象的__radd__
方法?1
这个对象是有__add__
方法的,并且可以使用。代码如下:
>>> (1).__add__(b)
4
究竟为什么1+b
会调用__radd__()
?
type(1) # int
type(b) # Nint
类型不同
If the right operand’s type is a subclass of the left operand’s type and that subclass provides the reflected method for the operation, this method will be called before the left operand’s non-reflected method.
如果右操作数的类型是左操作数类型的子类,并且该子类提供了操作的反射方法,则该方法将在左操作数的非反射方法之前被调用。
@郭帅
Nint 是 int 的子类