Skip to main content
 首页 » 编程设计

python之使用 __eq__ 在 Python 中修改类

2025年05月04日14duanxz

我需要添加一个 eq 方法,如果坐标指的是平面中的同一点(即具有相同的 x 和 y 坐标),该方法返回 True 并且我对如何做到这一点感到困惑。

我已经使用 eq 尝试了一些代码,但我仍然遇到错误,我不太清楚为什么。

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__(Coordinate, otherPoint): 
        if self.GetX() == otherPoint.getX()&& self.GetY() == otherPoint.getY() 
            return True 
 
x=5 
y=5 

如果两个坐标是相同的数字,则预期的输出将返回 true,如果 x 和 y 不是相同的数字,则预期的输出将返回 false。

请您参考如下方法:

代码中的一些问题/修复

  • 其实你不需要GetX和GetY,你可以直接引用属性x和y .
  • && 在 Python 中不是有效语法,您可以使用 and

  • __eq__ 的第一个参数将是 self

  • 如果你使用的是 python3.6+,你可以使用 f-strings 来格式化你的字符串,否则你可以使用格式化字符串
  • 您可以选择引发 TypeError 以确保 other 的类型为 Coordinate

因此更新后的代码看起来像

class Coordinate(object): 
    def __init__(self, x, y): 
        self.x = x 
        self.y = y 
 
    def __str__(self): 
        #Use a f-string to format your string representation 
        return f'<{self.x},{self.x}>' 
 
        #If python3.5 and below, you can use format string as below 
        #return '<{},{}>'.format(self.x, self.y) 
 
    def __eq__(self, other): 
        #If other is not an instance of Coordinate, raise TypeError 
        if not isinstance(other, Coordinate): 
            raise TypeError('An instance of class Coordinate is expected') 
        #Compare both coordinates and return True or False 
        return self.x == other.x and self.y == other.y 

然后你可以像下面这样使用这个类

c1 = Coordinate(5,5) 
c2 = Coordinate(6,6) 
 
print(c1) 
#<5,5> 
print(c2) 
#<6,6> 
print(c1 == c1) 
#True 
print(c1 == c2) 
#False 
print(c1 == 1) 
#TypeError: An instance of class Coordinate is expected