|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class Nint(int):
def __radd__(self, other):
print("__radd__ 被调用了!")
return int.__add__(self, other)
a = Nint(5)
b = Nint(3)
print(a + b)
c = int(1)
print(c + b)
执行结果:
8
__radd__ 被调用了!
4
按照我的理解,执行print(c+b)的时候,由于c是从int类型的实例,应该直接调用int类型的__add__(self,other)方法,为什么这里还会执行__radd__呢
本帖最后由 isdkz 于 2022-4-20 08:58 编辑
>>> b = Nint(3)
>>> b.__radd__
<bound method Nint.__radd__ of 3>
你可以看到 Nint 的 __radd__ 方法是 Nint.__radd__,
左操作数如果没有实现 Nint.__add__ 的话,Nint.__radd__ 就会被调用,
你再看一下 int 的 __add__:
>>> c = int(1)
>>> c.__add__
<method-wrapper '__add__' of int object at 0x72E79CE0>
>>>
int 的 add 方法是 method-wrapper '__add__' of int object ,并不是 Nint.__add__,
所以 Nint 的 __radd__ 方法就会被调用
|
|