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

前端 未结 5 1257
野趣味
野趣味 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:54

    You can return an iterator from your inner data:

    class Library (object):
      ...
      def __iter__(self):
        return self.books.itervalues()
    

    itervalues() returns an iterator to the values of the dictionary.

    If you want more control, you can make __iter__ a generator function

    class Library (object):
      ...
      def __iter__(self):
        for title in self.books:
          yield self.books[title]
    

    in this case, this generator yields the exact same as the iterator in the first example.

提交回复
热议问题