如何使用__getitem__和__iter__并从字典中返回值?

tho*_*mad 15 python iterator

我有一个带有字典的对象,我想通过__getitem__它来访问并迭代(仅值,键无关紧要),但我不知道该怎么做.

例如:

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
>>> 
Run Code Online (Sandbox Code Playgroud)

如何告诉它只需返回object字典中的每个项目(键无关紧要)?

Ale*_*lli 24

def __iter__(self): return self.books.itervalues()
Run Code Online (Sandbox Code Playgroud)