Python中__eq__方法实现出现Maximum recursion error问题排查
Let's break down what's going on here and fix the issue.
Why the Recursion Error Happens
Looking at your provided code, the immediate mistake that leads to unexpected behavior (and could indirectly cause recursion in edge cases) is that you're comparing method objects (self.getX and other.getX) instead of calling those methods to get the actual x/y values.
But if you're seeing a RecursionError, it's almost certainly due to an accidental loop in your __eq__ method—like if you mistakenly wrote self == other inside it. That would trigger __eq__ over and over again (since self == other invokes self.__eq__(other)), leading Python to hit its recursion limit.
Even without recursion, your current code will fail to correctly compare coordinates: self.getX is a bound method tied to the self instance, and other.getX is tied to other. These method objects will never be equal (even if x values are identical) because they're bound to different instances, so your __eq__ would incorrectly return False for matching coordinates.
The Fix
To resolve both the recursion risk and the broken equality check, here's what you need to do:
- Call the getter methods: Use
self.getX()(with parentheses) instead ofself.getXto retrieve the actual x value, same forgetY(). - Validate the
otherinstance: Check ifotheris aCoordinatefirst to avoid errors (and potential recursion) when comparing to non-Coordinate objects.
Here's the corrected code:
class Coordinate(object): def __init__(self,x,y): self.x = x self.y = y def getX(self): return self.x def getY(self): return self.y def __str__(self): return '<' + str(self.getX()) + ',' + str(self.getY()) + '>' def __eq__(self, other): # Ensure we're comparing to another Coordinate instance if not isinstance(other, Coordinate): return False # Compare the actual x and y values from the getter methods return self.getX() == other.getX() and self.getY() == other.getY() c = Coordinate(2, 3) d = Coordinate(2, 3) print(c == d) # Now outputs True as expected
Why This Works
- By calling
getX()andgetY(), we compare the actual numeric values of the coordinates, not the method objects themselves. - The
isinstancecheck ensures that if you try to compare a Coordinate to something non-Coordinate (like an integer), the method returnsFalseimmediately instead of throwing an error or entering an unintended loop.
内容的提问来源于stack exchange,提问作者code_conundrum

