首页 > 解决方案 > python运算符重载__radd__和__add__

问题描述

我目前正在学习 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)

我得到了以下结果

在此处输入图像描述

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

标签: pythonoperator-overloading

解决方案


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


然后,在你的__add__方法中,你这样做:

return self.val + other

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

但是int.__add__返回NotImplemented一个它不知道的类型,所以 Python 回退到调用other.__radd__.


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

return other + self.val

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


当然也int.__add__适用于另一个int,所以它返回你的内部的值+,你返回它,它返回一个内部__radd__的值,你返回,它返回一个顶层的值,你打印。+__add__+


推荐阅读