我可以在Python中使用对象(类的实例)作为字典键吗? [英] Can I use an object (an instance of a class) as a dictionary key in Python?
问题描述
我想将类实例用作字典键,例如:
I want to use a class instance as a dictionary key, like:
classinstance = class()
dictionary[classinstance] = 'hello world'
Python似乎无法将类作为字典键处理,还是我错了? 此外,我可以使用[[(classinstance,helloworld),...]之类的元组列表代替字典,但这看起来非常不专业. 您是否有解决此问题的线索?
Python seems to be not able to handle classes as dictionary key, or am I wrong? In addition, I could use a Tuple-list like [(classinstance, helloworld),...] instead of a dictionary, but that looks very unprofessional. Do you have any clue for fixing that issue?
推荐答案
您的实例需要可哈希化. Python词汇表告诉我们:
Your instances need to be hashable. The python glossary tells us:
如果对象的哈希值在其生命周期内始终不变(需要使用
__hash__()
方法),并且可以与其他对象进行比较(需要使用__eq__()
或__cmp__()
方法),则该对象是可哈希的.比较相等的可哈希对象必须具有相同的哈希值.
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.
可哈希性使对象可用作字典键和set成员,因为这些数据结构在内部使用哈希值.
Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
Python的所有不可变内置对象都是可哈希的,而没有可变容器(例如列表或字典)是可哈希的.默认情况下,作为用户定义类实例的对象是可哈希的.它们都比较不相等,并且其哈希值是其id().
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中使用对象(类的实例)作为字典键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!