`__eq__`实现中的最大递归错误

时间:2018-05-22 06:37:57

标签: python

class Coordinate(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def getX(self):
        # Getter method for a Coordinate object's x coordinate.
        # Getter methods are better practice than just accessing an attribute directly
        return self.x

    def getY(self):
        # Getter method for a Coordinate object's y coordinate
        return self.y

    def __str__(self):
        return '<' + str(self.getX()) + ',' + str(self.getY()) + '>'

    def __eq__(self, other):
        if self.getX == other.getX and self.getY == other.getY:
            return True
        else:
            return False        

c = Coordinate(2, 3)
d = Coordinate(2, 3)

c == d

1 个答案:

答案 0 :(得分:1)

您的__eq__方法应该是这样的:

它避免了立即比较不同类型的对象和错误警报,并避免使用getter intra class。

def __eq__(self, other):
    if self.__class__.__name__ == self.__class__.__name__:
        return self.x == other.x and self.y == other.y
    else:
        raise NotImplementedError

或在python&gt; 3.3:

def __eq__(self, other):
    if self.__class__.__qualname__ == self.__class__.__qualname__:
        return self.x == other.x and self.y == other.y
    else:
        raise NotImplementedError