What's the difference between __iter__ and __getitem__?

前端 未结 3 1967
情书的邮戳
情书的邮戳 2020-12-14 03:01

This happens in Python 2.7.6 and 3.3.3 for me. When I define a class like this

class foo:
    def __getitem__(self, *args):
        print(*args)
3条回答
  •  [愿得一人]
    2020-12-14 03:29

    To get the result you are expecting, you need to have a data element with limited len and return each in sequence:

    class foo:
        def __init__(self):
            self.data=[10,11,12]
    
        def __getitem__(self, arg):
            print('__getitem__ called with arg {}'.format(arg))
            return self.data[arg]
    
    bar = foo()
    for i in bar:
        print('__getitem__ returned {}'.format(i)) 
    

    Prints:

    __getitem__ called with arg 0
    __getitem__ returned 10
    __getitem__ called with arg 1
    __getitem__ returned 11
    __getitem__ called with arg 2
    __getitem__ returned 12
    __getitem__ called with arg 3
    

    Or you can signal the end of the 'sequence' by raising IndexError (although StopIteration works as well...):

    class foo:
        def __getitem__(self, arg):
            print('__getitem__ called with arg {}'.format(arg))
            if arg>3:
                raise IndexError
            else:    
                return arg
    
    bar = foo()
    for i in bar:
        print('__getitem__ returned {}'.format(i))   
    

    Prints:

    __getitem__ called with arg 0
    __getitem__ returned 0
    __getitem__ called with arg 1
    __getitem__ returned 1
    __getitem__ called with arg 2
    __getitem__ returned 2
    __getitem__ called with arg 3
    __getitem__ returned 3
    __getitem__ called with arg 4
    

    The for loop is expecting either IndexError or StopIteration to signal the end of the sequence.

提交回复
热议问题