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__
。由于它们是不相关的类型int
和Commuter1
,因此它首先尝试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__
+
归档时间: |
|
查看次数: |
8121 次 |
最近记录: |