在python中为什么Hash不检查具有相同散列和标识的对象的相等性?

时间:2016-12-01 18:34:19

标签: python python-2.7

Python通过在发生冲突时检查相等性来解决哈希冲突。为什么'a in s'不检查平等但's in s'呢?是否在哈希()和 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

1 个答案:

答案 0 :(得分:2)

Python容器假设所有元素都等于它们自己。他们使用的等式比较例程在尝试更昂贵的is之前会进行==检查。自a is a起,==检查就会被跳过。