Rob*_*eph 11 python equality set
我遇到了一个问题,我将一个实例添加到一个集合中,然后进行测试以查看该集合中是否存在该对象.我已经覆盖了__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"
Run Code Online (Sandbox Code Playgroud)
jte*_*ace 12
使用字典实现集合类.因此,对集合元素的要求与字典键的要求相同; 即,该元素定义__eq __()和__hash __().
所述__hash__函数文档表明异或部件的散列到一起.正如其他人所提到的,散列可变对象通常不是一个好主意,但如果你真的需要,这可行:
class DummyObj(object):
...
def __hash__(self):
return (hash(self.myTuple) ^
hash(tuple(self.myList)) ^
hash(tuple(self.myDictionary.items())))
Run Code Online (Sandbox Code Playgroud)
并检查它是否有效:
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
Run Code Online (Sandbox Code Playgroud)
这打印:
$ python settest.py
p1 in set True
p2 in set True
Run Code Online (Sandbox Code Playgroud)