gpt4 book ai didi

Python:键类型在字典中应该是不可变的,但为什么我可以让节点类的实例成为键?

转载 作者:太空宇宙 更新时间:2023-11-03 15:12:07 25 4
gpt4 key购买 nike

无论是python中的字典还是Java中的hash map,key都可以是节点类的实例。

但是当我阅读 python 教程时,它说:

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

感到困惑! # 对不起,我的表达不佳!:(

示例代码是:

class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None

dict = {}
node1 = RandomListNode(10)
node2 = RandomListNode(5)
dict[node1] = node2
print dict[node1].label #5

总结:Hashable(哈希值不会改变)或不可变对象(immutable对象)可以是键值。引用: https://docs.python.org/2/glossary.html#term-hashable

最佳答案

默认情况下,类的实例是唯一的,因此可以用作键。

实际约束是类中存在 __hash__ 方法。如果您添加自定义 __eq__ 方法,您还必须添加您自己的 __hash__ 方法,这样仍然被认为是“不可变的”——但要确保您的哈希值不会随突变而改变,否则您的条目将无法从 setdict 中检索。

关于Python:键类型在字典中应该是不可变的,但为什么我可以让节点类的实例成为键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25192554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com