简体   繁体   English

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

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

I'm reading Mark Summerfield's Programming in Python 3 book.我正在阅读 Mark Summerfield 的 Python 3 编程书。 In the chapter on OOP, he uses the below Circle class to demonstrate inheritance.在 OOP 一章中,他使用下面的 Circle 类来演示继承。 Regarding the __eq__ method, he states:关于__eq__方法,他说:

"This method compares this circle's radius with the other circle's radius and if they are equal it then explicitly call's the base class's __eq__ method using super() . If we did not use super() we would have infinite recursion, since Circle.__eq__() would then just keep calling itself. " “此方法将这个圆的半径与另一个圆的半径进行比较,如果它们相等,则使用super()显式调用基类的__eq__方法。如果我们不使用super()我们将有无限递归,因为Circle.__eq__()然后就会继续调用自己。”

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?如果__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)
        

To clarify, your question is:澄清一下,你的问题是:

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?有人能帮我理解为什么如果eq方法中的连接的第二部分不存在,我们会有无限递归吗?

From your description of your programming book, the author is not saying that infinite recursion would occur if the second part of the conjunction were not present.从你对你的编程书的描述来看,作者并不是说如果不存在连接的第二部分就会发生无限递归。 He is saying that infinite recursion would occur if the second part of the conjunction used Circle.__eq__(other) rather than super().__eq__(other) .他是说如果连接的第二部分使用Circle.__eq__(other)而不是super().__eq__(other)则会发生无限递归。

So, if the code said this:所以,如果代码是这样说的:

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

then infinite recursion happens because the Circle.__eq__(other) is just a function calling itself with no sort of control flow to exit the recursion.然后无限递归发生,因为Circle.__eq__(other)只是一个调用自身的函数,没有任何控制流来退出递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM