在python中-集合用于测试对象是否在集合中的运算符 [英] In python - the operator which a set uses for test if an object is in the set
问题描述
如果我有对象列表,则可以使用__cmp__
方法覆盖比较对象.这会影响==
运算符以及item in list
函数的工作方式.但是,它似乎并没有影响item in set
函数-我想知道如何更改MyClass对象,以便可以覆盖集合比较项目的行为.
If I have a list of objects, I can use the __cmp__
method to override objects are compared. This affects how the ==
operator works, and the item in list
function. However, it doesn't seem to affect the item in set
function - I'm wondering how I can change the MyClass object so that I can override the behaviour how the set compares items.
例如,我想创建一个在底部的三个打印语句中返回True的对象.此刻,最后一个打印语句返回False.
For example, I would like to create an object that returns True in the three print statements at the bottom. At the moment, the last print statement returns 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
推荐答案
set
使用__hash__
进行比较.改写它,你会很好的:
set
uses __hash__
for comparison. Override that, and you'll be good:
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
这篇关于在python中-集合用于测试对象是否在集合中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!