2011-12-30 40 views
10

如果我有一个对象列表,我可以使用__cmp__方法来覆盖对象进行比较。这会影响==操作员的工作方式以及item in list功能。但是,它似乎没有影响item in set函数 - 我想知道如何更改MyClass对象,以便我可以覆盖该行为如何比较项目的行为。在Python中 - 一个集合用于测试的运算符如果一个对象在集合中

例如,我想在底部的三个打印语句中创建一个返回True的对象。目前,最后的打印语句返回False。

class MyClass(object): 
    def __init__(self, s): 
     self.s = s 
    def __cmp__(self, other): 
     return cmp(self.s, other.s) 

instance1, instance2 = MyClass("a"), MyClass("a") 

print instance2==instance1    # True 
print instance2 in [instance1]   # True 
print instance2 in set([instance1]) # False 

回答

9

set使用__hash__进行比较。重写,而且你会好:

class MyClass(object): 
    def __init__(self, s): 
     self.s = s 
    def __cmp__(self, other): 
     return cmp(self.s, other.s) 
    def __hash__(self): 
     return hash(self.s) # Use default hash for 'self.s' 

instance1, instance2 = MyClass("a"), MyClass("a") 
instance3 = MyClass("b") 

print instance2==instance1    # True 
print instance2 in [instance1]   # True 
print instance2 in set([instance1]) # True 
+0

这是因为'set'实现使用字典存储(其中值都忽略)和字典包含操作('在dict_'键)用途'key'的散列。 – Noah 2011-12-30 14:58:34

相关问题