我遇到了一个问题,我将一个实例添加到一个集合中,然后进行测试以查看该对象是否存在于该集合中。我已经覆盖了__eq__()
但在包含测试期间不会调用它。我必须覆盖吗__hash__()
反而?如果是这样,我将如何实施__hash__()
鉴于我需要对元组、列表和字典进行哈希处理?
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"
来自关于集合的文档 https://docs.python.org/2/library/sets.html:
集合类是使用字典实现的。据此,
集合元素的要求与字典相同
钥匙;也就是说,该元素定义了 __eq__() 和 __hash__()。
The __hash__ 函数文档 https://docs.python.org/2/reference/datamodel.html#object.__hash__建议将组件的哈希值异或在一起。正如其他人提到的,对可变对象进行散列通常不是一个好主意,但如果您确实需要,那么这是可行的:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)