无法理解__add__函数中的一些错误

问题描述 投票:0回答:1

当我在Python中学习类时。我遇到了以下问题:

    1.
class Try_int(int):
    def __add__(self, other):
        return int(self) + int(other)
    2.
class Try_int(int):
    def __add__(self, other):
        return self + other

第一个给出了正确的答案。但第二个给出无限递归。

为什么会出现此问题?

|  __add__(self, value, /)
|      Return self+value.

事实上,我通过add检查了help(int)。它似乎与案例2相同。

python operator-overloading
1个回答
0
投票

原因如下:

在你的第一堂课中,你将selfother转换为int。这意味着self + other委托给int.__add__(self, other)。请注意,当您调用dir(int)时,您获得的是文档,而不是该方法的实际实现,即C语言。

因此,方法调用链是:

Try_int.__add__ -> int.__add__int.__add__不是递归的。

但是,在你的第二节课中,你没有在self上进行任何转换。这意味着当您尝试执行self + other时,Python将查找为__add__定义的self方法。但是,它确切地定义在您调用它的位置!这导致以下方法调用链:

Try_int.__add__ -> Try_int.__add__ -> Try_int.__add__ -> ...,当然是无限递归。

© www.soinside.com 2019 - 2024. All rights reserved.