2016-12-01 45 views
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 
+0

在cpython中,“is”检查是在'Objects/setobject.c :: set_lookkey'中用C语句'if(startkey == key)return entry;'完成的。 – tdelaney

+0

感谢您的python参考!这个实现是我一直在寻找的。 –

回答

2

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

相关问题