【发布时间】:2016-12-02 02:47:50
【问题描述】:
Python 通过检查是否存在冲突来解决哈希冲突。为什么 'a in s' 不检查相等而 'b in s' 呢? 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
【问题讨论】:
-
在 cpython 中,“is”检查是在
Objects/setobject.c::set_lookkey中使用 C 语句if (startkey == key) return entry;完成的。 -
感谢python参考!我一直在寻找那个实现。
标签: python python-2.7