How do I use __getitem__ and __iter__ and return values from a dictionary?

前端 未结 5 1259
野趣味
野趣味 2020-12-28 18:20

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.

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 19:01

    >>> class Library(object):
    ...     def __init__(self):                                                     
    ...             self.books = { 'title' : object, 'title2' : object, 'title3' : object, }
    ...     def __getitem__(self, i):
    ...             return self.books[i]
    ...     def __iter__(self):
    ...             return self.books.itervalues()
    ... 
    >>> library = Library()
    >>> library['title']
    
    >>> for book in library:
    ...     print book
    ... 
    
    
    
    

提交回复
热议问题