gpt4 book ai didi

python - 我可以使用对象(类的实例)作为 Python 中的字典键吗?

转载 作者:太空狗 更新时间:2023-10-29 17:55:58 28 4
gpt4 key购买 nike

我想使用类实例作为字典键,例如:

classinstance = class()
dictionary[classinstance] = 'hello world'

Python 似乎无法将类作为字典键来处理,或者我错了吗?此外,我可以使用像 [(classinstance, helloworld),...] 这样的元组列表来代替字典,但这看起来很不专业。您有解决该问题的线索吗?

最佳答案

您的实例需要是可哈希的。 python glossary告诉我们:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

关于python - 我可以使用对象(类的实例)作为 Python 中的字典键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7560172/

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