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

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

    __getitem__(self,key), where key is a integer, as your self.books is a dictionary and you can not do self.books[integer]

    e.g:

    >>>d = {'a':'sdsdsd','b':'sfsdsd'}
    >>d[0]
    
    d[0]
    Traceback (most recent call last):
      File "", line 1, in 
    KeyError: 0
    

    the iteration protocol goes like this:

    The iterator protocol consists of two methods. The __iter__() method, which must return the iterator object and the next() method, which returns the next element from a sequence. previously when __iter__ method was not defined, it fell back to __getitem__ by successively calling __getitem__ with increasing values till it gives index out of range error.

提交回复
热议问题