Python _add_uvs_uradd:表达式是如何计算的? 让我们考虑下一个类的例子: 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

Python _add_uvs_uradd:表达式是如何计算的? 让我们考虑下一个类的例子: 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,python,Python,所以,当我计算下列表达式时 a1 = A1() a2 = A2() print(a1 + a1, a2 + a2, a1 + a2, a2 + a1) 我得到这个结果: 222 111 666 222 我知道我是如何得到222、111、222的,但是a1+a2的计算结果怎么可能是666?a1是否有add方法,其中other是A2的一个实例,结果是111而不是666 我使用的Python版本是3.8.2,我认为A2在这种情况下也有A1的实例,它返回666。我认为A2在这种情况下也有A1的实例,

所以,当我计算下列表达式时

a1 = A1()
a2 = A2()
print(a1 + a1, a2 + a2, a1 + a2, a2 + a1)
我得到这个结果:

222 111 666 222
我知道我是如何得到222、111、222的,但是a1+a2的计算结果怎么可能是666?a1是否有add方法,其中other是A2的一个实例,结果是111而不是666


我使用的Python版本是3.8.2,我认为A2在这种情况下也有A1的实例,它返回666。

我认为A2在这种情况下也有A1的实例,它返回666。

x+y
中,如果
y
x
类的子类的实例,
y.\uuuu radd\uuuu
x.\uuuu add\uuuu
之前尝试。您可以在这里看到。

x+y
中,如果
y
x
类的子类的一个实例,
y.。\uu radd\uuuuuuu
x.\uu add\uuuuuu
之前被尝试过。您可以在这里看到。

在python 2.7中,它会打印(22211111.222)。您使用哪个版本的python?@napuzba我使用的是python 2.7中的3.8.2版本(22211111.222)。你使用哪个版本的python?@napuzba我使用的是3.8.2为什么python2和python3之间有区别?@napuzba:你需要有
A1
显式继承自python2上的
object
,或者你得到一个老式类,它有各种奇怪的特性,不应该使用。是的,如果A1继承自object-其工作方式相同。为什么python2和python3之间存在差异?@napuzba:在Python 2上,您需要
A1
显式继承自
object
,否则您会得到一个老式类,它有各种奇怪的怪癖,不应该使用。是的,如果A1继承自对象,则其工作方式相同。