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().
以下代码运行良好,因为默认情况下,类对象是散列的:
输出: 你好,世界
此外,对于更高级的用法,您应该阅读以下文章:
Object of custom type as dictionary key
你的实例需要是散列的。python glossary告诉我们:
尝试在类中实现hash和eq方法。
例如,下面是我创建的一个简单的哈希字典类:
相关问题 更多 >
编程相关推荐