Python通过检查是否存在冲突来解决哈希冲突。为什么'a in s‘不检查相等,而'b in s’检查?在散列()和eq()之间是否调用id()?
In [107]: class Foo(object):
...: def __eq__(self, other):
...: print "equality"
...: return False
...: def __ne__(self, other):
...: print "not equality"
...: return not self == other
...: def __hash__(self):
...: print "hash"
...: return 7
...: a = Foo()
...: b = Foo()
...: s = set()
...:
In [108]: s.add(a)
hash
In [109]: a in s
hash
Out[109]: True
In [110]: b in s
hash
equality
Out[110]: False发布于 2016-12-01 18:47:50
Python容器假定所有元素都等于它们自己。他们使用的相等比较例程在尝试更昂贵的is之前会进行==检查。从a is a开始,跳过==检查。
https://stackoverflow.com/questions/40917986
复制相似问题