gpt4 book ai didi

python - 如何实现 __eq__ 进行集合包含测试?

转载 作者:太空狗 更新时间:2023-10-29 18:06:11 25 4
gpt4 key购买 nike

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

最佳答案

来自documentation on sets :

The set classes are implemented using dictionaries. Accordingly, the requirements for set elements are the same as those for dictionary keys; namely, that the element defines both __eq__() and __hash__().

__hash__ function documentation建议将组件的哈希值异或在一起。正如其他人所提到的,散列可变对象通常不是一个好主意,但如果你真的需要,这行得通:

class DummyObj(object):

...

def __hash__(self):
return (hash(self.myTuple) ^
hash(tuple(self.myList)) ^
hash(tuple(self.myDictionary.items())))

并检查它是否有效:

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

这打印:

$ python settest.py 
p1 in set True
p2 in set True

关于python - 如何实现 __eq__ 进行集合包含测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15326985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com