python是否有碰撞,通过检查平等来解决哈希碰撞。为什么" a in s"不检查平等,而是" b in s"中的" b"?在 Hash ()和 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
python容器都假定所有元素都等于自己。在尝试更昂贵的==
之前,他们使用的平等比较程序进行了is
检查。由于a is a
,==
检查被跳过。