I'm reading Mark Summerfield's Programming in Python 3 book. In the chapter on OOP, he uses the below Circle class to demonstrate inheritance. Regarding the __eq__
method, he states:
"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. "
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?
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)
CodePudding user response:
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?
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)
.
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.