如何拥有同时具有元组和字典特征的数据结构 [英] How to have data structure with both tuple and dictionary characteristic
问题描述
通过引用代码
http://initd.org/psycopg/docs/extras.html#dictionary-like-cursor
<预><代码>>>>rec['数据']abc'def">>>记录[2]abc'def"我想知道他们是如何设法制作具有元组和字典特征的数据结构的?
在 Python 中,[]
查找由 __getitem__
魔术方法处理;换句话说,当您索引自定义类时,Python 将调用 instance.__getitem__(...)
并返回值.这可以让你做例如
有几种自然的方式来维护实际的数据结构;可能最简单的方法是维护一个字典和一个列表,并根据键的类型对其中之一进行索引.
注意这是不自然的;你会期望一个类似 dict 的对象将 0
视为一个键.可能值得编写一种不同的方法,例如index
处理索引.
您可能还希望实现 __setitem__
和 __contains__
方法.
By refering code at
http://initd.org/psycopg/docs/extras.html#dictionary-like-cursor
>>> rec['data']
"abc'def"
>>> rec[2]
"abc'def"
I was wondering how they manage to make a data structure having both tuple and dictionary characteristic?
In Python the []
lookups are handled by the __getitem__
magic method; in other words, when you index a custom class Python will call instance.__getitem__(...)
and return you the value. This lets you do e.g.
>>> class Foo:
... def __getitem__(self, value):
... return value
...
>>> foo = Foo()
>>> foo["1"]
'1'
>>> foo[0]
0
There are several natural ways of maintaining the actual data structure; probably the easiest is to maintain both a dict and a list and index into one of them depending on the type of the key.
Notice that this is unnatural; you would expect a dict-like object to treat 0
as a key. it might be worth writing a different method e.g. index
to handle the indexing.
You may also wish to implement the __setitem__
and __contains__
methods.
这篇关于如何拥有同时具有元组和字典特征的数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!