我可以使用可变对象作为python中的字典键。这不是不允许的吗? [英] I'm able to use a mutable object as a dictionary key in python. Is this not disallowed?

查看:480
本文介绍了我可以使用可变对象作为python中的字典键。这不是不允许的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$(


$ bi = A()
d = {}

d [i] = 2

打印d

ix = 10

打印d
pre>

我以为只有不变的对象可以是字典键,但上面的对象是可变的。

解决方案

任何具有 __hash__ 的对象方法可以是字典键。对于你写的类,这个方法默认是返回一个基于id(self)的值,如果这些类不是通过身份确定相等的,那么你可能会惊奇地使用它们作为键:

 >>> A类(对象):
... def __eq __(self,other):
... return True
...
>>>一,二= A(),A()
>>>> d = {one:one}
>>>> one == two
True
>>> d [one]
'one'
>>> d [two]
追溯(最近的最后一次呼叫):
文件< stdin>,第1行,< module>
KeyError:< __ main __。0xb718836c的对象>

>>> hash(set())#sets不能是dict键
追溯(最近的最后一次调用):
文件< stdin>,第1行在< module>
TypeError:unhashable类型:'set'




版本2.6:__hash__现在可以设置为None,以将类的实例显式标记为不可分。 [ __hash__ ]




  class Unhashable(object):
__hash__ =无


class A(object):
    x = 4

i = A()
d = {}

d[i] = 2

print d

i.x = 10

print d

I thought only immutable objects can be dictionary keys, but the object i above is mutable.

解决方案

Any object with a __hash__ method can be a dictionary key. For classes you write, this method defaults to returning a value based off id(self), and if equality is not determined by identity for those classes, you may be surprised by using them as keys:

>>> class A(object):
...   def __eq__(self, other):
...     return True
... 
>>> one, two = A(), A()
>>> d = {one: "one"}
>>> one == two
True
>>> 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 keys
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

Changed in version 2.6: __hash__ may now be set to None to explicitly flag instances of a class as unhashable. [__hash__]

class Unhashable(object):
  __hash__ = None

这篇关于我可以使用可变对象作为python中的字典键。这不是不允许的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆