0

我在模块中有一个如下声明的python类

class Position:
def __init__(self, x, y):
    self.x = int(x)
    self.y = int(y)
def __str__(self):
    return self.toString()
def toString(self): #deprecated
    return "{x:"+str(self.x)+" y:"+str(self.y)+"}"

现在,稍后在主程序中,我进行如下比较:

can_pos = somestreet.endOfStreet(curPos).getPos() #returns a Position object
if(can_pos == atPos): # this returns False
  #blafoo
#if(can_pos.x == atPos.x and can_pos.y == atPos.y): #this returns True (and is expected)

我不明白不同行为的原因可能是什么......

如果有人能给我一个提示,那就太好了:)

提前致谢

4

1 回答 1

3

__eq__如评论中所述,您至少需要__ne__明确定义:

class Position:
    def __init__(self, x, y):
        self.x = int(x)
        self.y = int(y)
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y
    def __ne__(self, other):
        return not self == other

这使

>>> a = Position(1,2)
>>> b = Position(1,2)
>>> c = Position(2,3)
>>> a == b
True
>>> a == c
False
>>> b == c
False
>>> a != a
False
>>> a != b
False
>>> a != c
True

但是请注意,与 Python 2 相比,您将拥有:

>>> a > c
True

和其他可能不受欢迎的行为,而在 Python 3(你正在使用的)中你会得到

TypeError: unorderable types: Position() > Position()
于 2012-02-08T20:02:54.733 回答