【问题标题】:In python why does Hash not check equality for objects with same hash and identity?在 python 中,为什么哈希不检查具有相同哈希和身份的对象的相等性?
【发布时间】: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


【解决方案1】:

Python 容器假定所有元素都与自身相同。他们使用的相等比较例程会在尝试更昂贵的== 之前进行is 检查。由于a is a,== 检查被跳过。

【讨论】:

    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 2012-08-13
    相关资源
    最近更新 更多