我遇到了一个问题,即将实例添加到集合中,然后再进行测试以查看该集合中是否存在该对象。我已覆盖__eq__()
,但在包含测试期间它不会被调用。我必须重写__hash__()
吗?如果是这样,我将如何实现__hash__()
,因为我需要散列元组,列表和字典?如何实现__eq__集合包含测试?
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'中的p1。我应该得到别的东西吗? – hughdbrown 2013-03-10 20:11:30
散列可变对象通常不是一个好主意... – mgilson 2013-03-10 20:11:53
请参阅http://wiki.python.org/moin/DictionaryKeys,为什么@mgilson是正确的。 – delnan 2013-03-10 20:12:32