如何实现__eq__进行集合包含测试? [英] How to implement __eq__ for set inclusion test?
问题描述
我遇到了一个问题,即将实例添加到集合中,然后进行测试以查看该对象是否存在于集合中。我已覆盖 __ eq __()
,但是在包含测试期间未调用它。我是否必须改写 __ hash __()
?如果是这样,鉴于我需要对元组,列表和字典进行哈希处理,我将如何实现 __ hash __()
?
I am running into an issue where I'm adding an instance to a set and then later testing to see whether or not that object exists in that set. I've overridden __eq__()
but it doesn't get called during the inclusion test. Do I have to override __hash__()
instead? If so, how would I implement __hash__()
given that I need to hash the tuple, the list, and the dictionary?
class DummyObj(object):
def __init__(self, myTuple, myList, myDictionary=None):
self.myTuple = myTuple
self.myList = myList
self.myDictionary = myDictionary
def __eq__(self, other):
return self.myTuple == other.myTuple and \
self.myList == other.myList and \
self.myDictionary == other.myDictionary
def __ne__(self, other):
return not self.__eq__(other)
if __name__ == '__main__':
list1 = [1, 2, 3]
t1 = (4, 5, 6)
d1 = { 7 : True, 8 : True, 9 : True }
p1 = DummyObj(t1, list1, d1)
mySet = set()
mySet.add(p1)
if p1 in mySet:
print "p1 in set"
else:
print "p1 not in set"
推荐答案
从关于文档的文档:
set类使用字典来实现。因此,set元素的
要求与字典
键的要求相同;也就是说,该元素同时定义了__eq __()和__hash __()。
The set classes are implemented using dictionaries. Accordingly, the requirements for set elements are the same as those for dictionary keys; namely, that the element defines both __eq__() and __hash__().
__ hash__函数文档建议将各组成部分的哈希值进行异或运算。正如其他人提到的那样,对可变对象进行散列通常不是一个好主意,但是,如果您确实需要,可以这样做:
The __hash__ function documentation suggests xor-ing the hashes of components together. As others have mentioned, it's generally not a good idea to hash mutable objects, but if you really need to, this works:
class DummyObj(object):
...
def __hash__(self):
return (hash(self.myTuple) ^
hash(tuple(self.myList)) ^
hash(tuple(self.myDictionary.items())))
并检查其是否有效:
p1 = DummyObj(t1, list1, d1)
p2 = DummyObj(t1, list1, d1)
mySet = set()
mySet.add(p1)
print "p1 in set", p1 in mySet
print "p2 in set", p2 in mySet
此打印:
$ python settest.py
p1 in set True
p2 in set True
这篇关于如何实现__eq__进行集合包含测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!