我有一个带有字典的对象,我想通过 __getitem__ 访问该对象并对其进行迭代(仅值,键无关紧要),但不知道该怎么做.p>
例如:
Python 2.5.2 (r252:60911, Jul 22, 2009, 15:33:10)>>>类库(对象):... def __init__(self):... self.books = {'title':对象,'title2':对象,'title3':对象,}... def __getitem__(self, i):...返回 self.books[i]...>>>图书馆=图书馆()>>>图书馆['标题']<输入对象">>>>图书馆借书:... 打印书...回溯(最近一次通话最后):<module> 中的文件<stdin>"第 1 行文件<stdin>",第 5 行,在 __getitem__ 中关键错误:0>>>我如何告诉它为字典中的每个项目简单地返回 object (键无关紧要)?
def __iter__(self): return self.books.itervalues()I have an object with a dictionary that I want to access via __getitem__ as well as iterate over (values only, keys don't matter) but am not sure how to do it.
For example:
Python 2.5.2 (r252:60911, Jul 22 2009, 15:33:10)
>>> class Library(object):
... def __init__(self):
... self.books = { 'title' : object, 'title2' : object, 'title3' : object, }
... def __getitem__(self, i):
... return self.books[i]
...
>>> library = Library()
>>> library['title']
<type 'object'>
>>> for book in library:
... print book
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __getitem__
KeyError: 0
>>>
How do I tell it to simply return the object for each item in the dictionary (the key doesn't matter) ?
def __iter__(self): return self.books.itervalues()
这篇关于如何使用 __getitem__ 和 __iter__ 并从字典中返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
使用 python 解析非常大的 xml 文件时出现问题Troubles while parsing with python very large xml file(使用 python 解析非常大的 xml 文件时出现问题)
使用 Python 2 在 XML 中按属性查找所有节点Find all nodes by attribute in XML using Python 2(使用 Python 2 在 XML 中按属性查找所有节点)
Python - 如何解析 xml 响应并将元素值存储在变量中Python - How to parse xml response and store a elements value in a variable?(Python - 如何解析 xml 响应并将元素值存储在变量中?)
如何在 Python 中获取 XML 标记值How to get XML tag value in Python(如何在 Python 中获取 XML 标记值)
如何使用 ElementTree 正确解析 utf-8 xml?How to correctly parse utf-8 xml with ElementTree?(如何使用 ElementTree 正确解析 utf-8 xml?)
将 XML 从 URL 解析为 python 对象Parse XML from URL into python object(将 XML 从 URL 解析为 python 对象)