具有hash方法的任何对象都可以是字典键。对于您编写的类,此方法默认返回基于id(self)的值,并且如果相等性不是由这些类的标识决定的,则将它们用作键可能会让您感到惊讶:
>>> class A(object):... def __eq__(self, other):... return True... >>> one, two = A(), A()>>> d = {one: "one"}>>> one == twoTrue>>> d[one]'one'>>> d[two]Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: <__main__.A object at 0xb718836c>>>> hash(set()) # sets cannot be dict keysTraceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unhashable type: 'set'在2.6版中进行了更改:__hash__现在可以设置为None,以将类实例明确标记为不可哈希。[
hash
]
class Unhashable(object): __hash__ = None



