_add_vs_add_:如何计算表达式



让我们考虑下一个类示例:

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

我知道我是如何得到222111222的,但a1+a2怎么可能计算为666?a1是否有加法方法,而其他是A2的实例,这将导致111而不是666?

我使用的Python版本是3.8.2

x + y中,如果yx类的子类的实例,则在x.__add__之前尝试y.__radd__。你在这里看到了。

我相信A2在这种情况下也有A1的实例,它毕竟返回666。

最新更新