如何拥有同时具有元组和字典特征的数据结构 [英] How to have data structure with both tuple and dictionary characteristic

查看:37
本文介绍了如何拥有同时具有元组和字典特征的数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过引用代码

http://initd.org/psycopg/docs/extras.html#dictionary-like-cursor

<预><代码>>>>rec['数据']abc'def">>>记录[2]abc'def"

我想知道他们是如何设法制作具有元组和字典特征的数据结构的?

解决方案

在 Python 中,[] 查找由 __getitem__ 魔术方法处理;换句话说,当您索引自定义类时,Python 将调用 instance.__getitem__(...) 并返回值.这可以让你做例如

<预><代码>>>>Foo类:... def __getitem__(self, value):... 返回值...>>>foo = foo()>>>foo[1"]'1'>>>富[0]0

有几种自然的方式来维护实际的数据结构;可能最简单的方法是维护一个字典和一个列表,并根据键的类型对其中之一进行索引.

注意这是不自然的;你会期望一个类似 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆