You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中__eq__方法实现出现Maximum recursion error问题排查

Analysis and Fix for Maximum Recursion Error in Coordinate.eq

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:

  1. Call the getter methods: Use self.getX() (with parentheses) instead of self.getX to retrieve the actual x value, same for getY().
  2. Validate the other instance: Check if other is a Coordinate first 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() and getY(), we compare the actual numeric values of the coordinates, not the method objects themselves.
  • The isinstance check ensures that if you try to compare a Coordinate to something non-Coordinate (like an integer), the method returns False immediately instead of throwing an error or entering an unintended loop.

内容的提问来源于stack exchange,提问作者code_conundrum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:30:34