你需要写一个__eq__
功能来定义如何比较对象是否相等。如果你想排序,那么你应该有一个__cmp__
函数,并且按照__cmp__
来实现__eq__
是最有意义的。
def __eq__(self, other):
return cmp(self, other) == 0
你或许应该还实现__hash__
,你绝对应该,如果你打算把你的对象为一组或字典。对象的默认__hash__
是id(),它有效地使所有对象都是唯一的(即唯一性不基于对象内容)。
我为一种类型的等价比较写了一个基类/接口。你可能会发现它有用:
class Comparable(object):
def attrs(self):
raise Exception("Must be implemented in concrete sub-class!")
def __values(self):
return (getattr(self, attr) for attr in self.attrs())
def __hash__(self):
return reduce(lambda x, y: 37 * x + hash(y), self.__values(), 0)
def __cmp__(self, other):
for s, o in zip(self.__values(), other.__values()):
c = cmp(s, o)
if c:
return c
return 0
def __eq__(self, other):
return cmp(self, other) == 0
def __lt__(self, other):
return cmp(self, other) < 0
def __gt__(self, other):
return cmp(self, other) > 0
if __name__ == '__main__':
class Foo(Comparable):
def __init__(self, x, y):
self.x = x
self.y = y
def attrs(self):
return ('x', 'y')
def __str__(self):
return "Foo[%d,%d]" % (self.x, self.y)
def foo_iter(x):
for i in range(x):
for j in range(x):
yield Foo(i, j)
for a in foo_iter(4):
for b in foo_iter(4):
if a<b: print "%(a)s < %(b)s" % locals()
if a==b: print "%(a)s == %(b)s" % locals()
if a>b: print "%(a)s > %(b)s" % locals()
派生类必须实现attrs()
返回有助于其身份(即不变的属性,使得它它是什么)对象的属性的元组或列表。最重要的是,代码在存在多个属性的情况下正确处理等同性,这是旧学校代码,通常不正确。
我认为他的问题是对象平等,而不是发现:) – extraneon 2010-04-01 08:39:47
OP有对象列表,而不是原子类型列表。如果你使用没有定义'__hash__'的对象来尝试你的代码,它将不起作用,就像OP的代码不能处理没有定义'__eq__'或'__cmp__'的对象列表一样。 – hughdbrown 2010-04-01 15:05:44