考虑以下 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: {}
该行为会令人困惑、不一致且无用。
关于python - 为什么可变实体不能是字典键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37197862/