我可以使用可變對象作為python中的字典鍵。這是不允許的嗎?
具有方法的任何對象都可以是字典鍵。對于您編寫的類,此方法默認返回基于id(self)的值,并且如果相等性不是由這些類的標(biāo)識決定的,則將它們用作鍵可能會讓您感到驚訝:
>>> 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__現(xiàn)在可以設(shè)置為None,以將類實例明確標(biāo)記為不可哈希。[]
class Unhashable(object): __hash__ = None解決方法
class A(object): x = 4i = A()d = {}d[i] = 2print di.x = 10print d
我以為只有不可變的對象才可以是字典鍵,但是上面的對象是可變的。
相關(guān)文章:
