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

前端 未结 5 1269
野趣味
野趣味 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 18:40

    Add this method to Library:

    def __iter__(self):
      return self.books.itervalues()
    

    This delegates iteration to the dict, which has an easy method to iterate values. Read about the iterator protocol, which consists of __iter__ (on all iterables) and next(__next__ in 3.x) (only on iterators) methods.

提交回复
热议问题