在python中,为什么Hash不检查具有相同散列和身份的对象的相等性? [英] In python why does Hash not check equality for objects with same hash and identity?

查看:42
本文介绍了在python中,为什么Hash不检查具有相同散列和身份的对象的相等性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 通过检查是否存在冲突来解决哈希冲突.为什么 'a in s' 不检查相等性而 'b in s' 呢?hash() 和 eq() 之间是否有对 id() 的调用?

Python resolves hash collisions by checking for equality if there is a collision. Why does 'a in s' not check for equality but 'b in s' does? Is there a call to id() between hash() and eq()?

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 是一个,所以跳过了== 检查.

Python containers assume that all elements are equal to themselves. The equality comparison routine they use does an is check before attempting the more expensive ==. Since a is a, the == check is skipped.

这篇关于在python中,为什么Hash不检查具有相同散列和身份的对象的相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆