素材牛VIP会员
关于Python中反运算方法何时会被调用的问题?
 ju***23  分类:Python  人气:950  回帖:1  发布于6年前 收藏

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__()

 标签:python

讨论这个帖子(1)垃圾回帖将一律封号处理……

Lv1 新人
qq***qq JS工程师 6年前#1

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 的子类

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取