2
Python通过在发生冲突时检查相等性来解决哈希冲突。为什么'a s'不检查平等,但是'b in s'呢?是否有呼叫ID()散列()和等式()?在Python中,为什么Hash不检查具有相同散列和标识的对象是否相等?
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
在cpython中,“is”检查是在'Objects/setobject.c :: set_lookkey'中用C语句'if(startkey == key)return entry;'完成的。 – tdelaney
感谢您的python参考!这个实现是我一直在寻找的。 –