考虑以下 Python 解释器 shell session :
>>> class D(dict):
... def __hash__(self):
... return id(self)
...
>>> d1 = D({'a': 'b'})
>>> d2 = D({'a1': 'b1'})
>>> t = {d1: 1, d2: 2}
>>> t[d1]
1
>>> t[d2]
2
为什么字典的 __hash__ 不默认为 id()?是什么导致了禁止使用可变实体作为字典键的设计决策?
请您参考如下方法:
Why doesn't dict's
__hash__default toid()?
因为这违反了相等对象具有相等哈希值的基本不变量。如果字典使用它们的 id 作为它们的哈希值,那么您将进行如下交互:
>>> x, y = {}, {}
>>> x == y
True
>>> hash(x) == hash(y)
False
>>> x[{}] = 3
>>> x[{}]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: {}
该行为会令人困惑、不一致且无用。
