用类作字典的 Key 能搞不?

2017-07-26 11:38:01 +08:00
 bccber
class Key:
def __init__(self, i, j):
self.i = i
self.j = j
pass

dic={};

key1 = Key(1, 1)
key2 = Key(1, 1)

dic.append(key1, 1)
dic.append(key2, 1)
4555 次点击
所在节点    Python
22 条回复
CryMeatel
2017-07-26 19:58:31 +08:00
@bccber 哈哈, 但实际上 tuple 是 python 文档里面推荐的可 hash 可对比的不变容器,用来做 Key 合适不过了。

不过你一定要确认的话,tuple 实现都是 C 代码,要看去看解释器源码了。
linw1995
2017-07-26 22:04:29 +08:00
>>> from collections.abc import Hashable
>>> mutable = [list, bytearray, set, dict]
>>> immutable = [int, float, complex, str, tuple, frozenset, bytes]
>>> all(isinstance(x(), Hashable) for x in immutable)
True
>>> all(issubclass(x, Hashable) for x in immutable)
True
>>> any(isinstance(x(), Hashable) for x in mutable)
False
>>> any(issubclass(x, Hashable) for x in mutable)

基本类型里,不可变的都是可 hash 的。无论是有序的 Tuple 还是无序的 frozenset,因为其是不可变的,都是可 hash 的。所以都可以当 mapping 的 key。
若是要自定义可 hash 的对象,就一定要实现__hash__、__eq__两个方法。
若是不实现,也可以 hash。这是因为类缺省__hash__、__eq__两个方法,但是其依据是 id 值,那么结果就不是我们想要的。

参考:
https://wiki.python.org/moin/DictionaryKeys#User_Defined_Types_as_Dictionary_Keys
http://www.laurentluce.com/posts/python-dictionary-implementation/

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/378035

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX