python字典的键可变吗_我可以使用可变对象作为python中的字典键。这不是不允许的吗?...

本文探讨了为何看似可变的类A实例在Python中不能直接用作字典键,以及如何通过自定义__eq__和__hash__方法解决这一问题。实例演示了如何让类A成为字典键,同时解释了在Python 2.6之后关于__hash__属性的更改。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

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 "", line 1, in

KeyError: <__main__.A object at 0xb718836c>

>>> hash(set()) # sets cannot be dict keys

Traceback (most recent call last):

File "", line 1, in

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.

class Unhashable(object):

__hash__ = None

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值