Skip to main content
 首页 » 编程设计

python之在 python 中,为什么哈希不检查具有相同哈希和身份的对象是否相等

2024年10月17日8leader

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 

请您参考如下方法:

Python 容器假定所有元素都等于它们自己。他们使用的相等比较例程在尝试更昂贵的 == 之前执行 is 检查。由于 a 是 a,因此跳过了 == 检查。