我遇到了一個問題,即將實例添加到集合中,然後再進行測試以查看該集合中是否存在該對象。我已覆蓋__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