Python 3.2.2自定义对象比较失败

时间:2012-02-08 19:51:59

标签: python python-3.x python-3.2

我有一个在模块中声明如下的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)

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

如果有人可以给我一个提示,那将是非常好的:)

提前致谢

1 个答案:

答案 0 :(得分: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()