Python通过在发生冲突时检查相等性来解决哈希冲突。为什么'a in s'不检查平等但's 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
答案 0 :(得分:2)
Python容器假设所有元素都等于它们自己。他们使用的等式比较例程在尝试更昂贵的is
之前会进行==
检查。自a is a
起,==
检查就会被跳过。