python 运算符重载 __radd__ 和 __add__

Tho*_*hor 3 python operator-overloading

我目前正在学习 python 运算符重载(__radd__准确地说__add__),我有以下代码

class Commuter1:
    def __init__(self, val):
        self.val = val
    def __add__(self, other):
        print('add', self.val, other)
        return self.val + other


    def __radd__(self, other):
        print('radd', self.val, other)
        return other + self.val


x = Commuter1(88)
y = Commuter1(99)

print(x + y)
Run Code Online (Sandbox Code Playgroud)

我得到了以下结果

在此输入图像描述

当单独使用时,我了解如何__radd__工作__add__。但对于 line x + y,我不确定为什么会调用__radd____add__方法。

aba*_*ert 11

x首先,Python 查看和的类型y来决定是否调用x.__add__y.__radd__。由于它们都是同一类型Commuter1,因此它x.__add__首先尝试。


然后,在您的__add__方法中执行以下操作:

return self.val + other
Run Code Online (Sandbox Code Playgroud)

self.val因此,Python 会查看和的类型other来决定是否调用self.val.__add__other.__radd__。由于它们是不相关的类型intCommuter1,因此它首先尝试int.__add__

int.__add__返回NotImplemented的类型是它不知道的,因此 Python 回退到调用other.__radd__.


在你的__radd__方法中,你这样做:

return other + self.val
Run Code Online (Sandbox Code Playgroud)

other因此,Python 会查看和的类型self.val来决定是否调用other.__add__self.val.__radd__。由于它们的类型相同int,因此它首先尝试__add__


当然,它int.__add__适用于另一个,因此它返回您的int内部的值,您返回的内部的值,您返回的内部的值,您返回的内部的值,您返回的内部的值,您打印的顶层的值。+__radd__+__add__+