我遇到了在那里我加入一个实例,以一组,然后后来的测试中看到该组中是否存在该对象的问题。 我已经覆盖__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"