How to implement __eq__ for set inclusion test?

最后都变了- 提交于 2019-12-05 00:47:11
jterrace

From the 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__().

The __hash__ function documentation suggests xor-ing the hashes of components together. As others have mentioned, it's generally not a good idea to hash mutable objects, but if you really need to, this works:

class DummyObj(object):

    ...

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

And checking to see if it works:

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

This prints:

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

Well, my guess would be __eq__ or __ne__ may not called by python when comparing objects using the 'in' operator. I'm not positive what the specific "rich comparison" operator would be, looking at the documentation, but overriding __cmp__ should solve your problem as python uses it by default to perform object comparisons if a more suitable "rich comparison" operator is not implemented.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!