让我们考虑使用类的下一个示例:
class A1:
def __init__ (self):pass
def __add__(self, other):
if isinstance(other, A2):return 111
if isinstance(other, A1):return 222
return 333
def __radd__(self, other):
if isinstance(other, A1):return 444
return 555
class A2(A1):
def __init__(self) : pass
def __radd__(self, other):
if isinstance(other, A1):return 666
return 777所以,当我计算以下表达式时
a1 = A1()
a2 = A2()
print(a1 + a1, a2 + a2, a1 + a2, a2 + a1)我得到了这个结果:
222 111 666 222我明白我是如何得到222,111,222的,但是a1 + a2怎么可能评估到666年呢?a1没有添加方法吗?其他是A2的一个实例,它将导致111个而不是666个?
我使用的Python版本是3.8.2
发布于 2020-12-03 20:12:39
在x + y中,如果y是x类子类的一个实例,则在x.__add__之前尝试y.__radd__。在这里可以看到这一点。
发布于 2020-12-03 20:06:00
我相信,在这种情况下,A2也有A1的实例,它最终返回666。
https://stackoverflow.com/questions/65133246
复制相似问题