python - 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__
方法。
解决方案
首先,Python 查看 和 的类型x
来y
决定是否调用x.__add__
或y.__radd__
。由于它们都是相同的 type Commuter1
,因此它首先尝试x.__add__
。
然后,在你的__add__
方法中,你这样做:
return self.val + other
因此,Python 会查看 和 的类型self.val
来other
决定是否调用self.val.__add__
或other.__radd__
。由于它们是不相关的类型int
and Commuter1
,它首先尝试int.__add__
。
但是int.__add__
返回NotImplemented
一个它不知道的类型,所以 Python 回退到调用other.__radd__
.
在你的__radd__
方法中,你这样做:
return other + self.val
因此,Python 会查看 和 的类型other
来self.val
决定是否调用other.__add__
或self.val.__radd__
。由于它们都是相同的类型int
,因此它首先尝试__add__
。
当然也int.__add__
适用于另一个int
,所以它返回你的内部的值+
,你返回它,它返回一个内部__radd__
的值,你返回,它返回一个顶层的值,你打印。+
__add__
+
推荐阅读
- java - 为什么我无法使用 HTMLUnit Java 连接到该站点
- python - 根据列表中值的顺序对键进行排序
- c - 三种颜色三角形
- sql - SQL 按日期聚合
- c# - 如何使用 Ajax 和 C# 从数据库中填充 FullCalendar
- python - PyOpenGL 片段着色器纹理采样
- python - 如何在不使用模块的情况下使用每行的字数在python中拆分文本文件
- ios - 如何使用委托方法从捕获会话中提取视频?
- python - Itertools 循环方法——为什么是“while”循环?
- python - 没有出现在 Tensorflow-PyCharm IDE 中的可视化