如何使用__getitem__和__iter__并从字典中返回值? [英] How do I use __getitem__ and __iter__ and return values from a dictionary?

查看:225
本文介绍了如何使用__getitem__和__iter__并从字典中返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有字典的对象,我想通过__getitem__访问它并进行迭代(仅值,键无关紧要),但不确定如何执行.

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.

例如:

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
>>> 

我如何告诉它为字典中的每个项目简单地返回object(键无关紧要)?

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__并从字典中返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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