无限递归:为什么会出现在这个class方法的实现中

Infinite recursion: why does it occur in the implementation of this class method

我正在阅读 Mark Summerfield 的《编程》Python 第 3 本书。在 OOP 的章节中,他使用下面的 Circle class 来演示继承。关于 __eq__ 方法,他说:

"此方法比较这个圆的半径与另一个圆的半径,如果它们相等,则使用 super() 显式调用基础 class 的 __eq__ 方法。如果我们不使用 super() 我们会无限递归,因为 Circle.__eq__() 会继续调用自己。“

如果 __eq__ 方法中连词的第二部分不存在,谁能帮我理解为什么我们会有无限递归?

class Circle(Point):

    def __init__(self, radius, x=0, y=0):
        super().__init__(x, y)
        self.radius = radius


    def edge_distance_from_origin(self):
        return abs(self.distance_from_origin() - self.radius)


    def area(self):
        return math.pi * (self.radius ** 2)


    def circumference(self):
        return 2 * math.pi * self.radius


    def __eq__(self, other):
        return self.radius == other.radius and super().__eq__(other)


    def __repr__(self):
        return "Circle({0.radius!r}, {0.x!r}, {0.y!r})".format(self)


    def __str__(self):
        return repr(self)
        

澄清一下,你的问题是:

Can someone help me understand why we would have infinite recursion if the second part of the conjunction in the eq method were not present?

根据您对编程书的描述,作者并不是说如果不存在连词的第二部分就会发生无限递归。他是说如果连词的第二部分使用 Circle.__eq__(other) 而不是 super().__eq__(other).

就会发生无限递归

所以,如果代码这样说:

def __eq__(self, other):
        return self.radius == other.radius and Circle.__eq__(other)

然后无限递归发生,因为 Circle.__eq__(other) 只是一个函数调用自身,没有任何控制流来退出递归。