我想了解引擎盖下的python哈希函数。我创建了一个自定义类,其中所有实例都返回相同的散列值。
class C(object):
def __hash__(self):
return 42
我只是假设上面的类中只有一个实例可以在任何时候在一个集合中,但实际上一个集合可以有多个具有相同哈希的元素。
c, d = C(), C()
x = {c: 'c', d: 'd'}
print x
# {<__main__.C object at 0x83e98cc>:'c', <__main__.C object at 0x83e98ec>:'d'}
# note that the dict has 2 elements
我进行了一些尝试,发现如果我重写该__eq__
方法使得该类的所有实例比较相等,那么该集只允许一个实例。
class D(C):
def __eq__(self, other):
return hash(self) == hash(other)
p, q = D(), D()
y = {p:'p', q:'q'}
print y
# {<__main__.D object at 0x8817acc>]: 'q'}
# note that the dict has only 1 element
所以我很想知道一个字典如何具有相同散列的多个元素。
相似问题