我遇到了一个问题,我将一个实例添加到集合中,然后进行测试以查看该对象是否存在于该集合中。我已经覆盖__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"