0

When we implement our own obj in python which support for i in obj statement, what magic method we need to create?

Is there a link to the official document that I can check?

During my reading of some other's source code, I found there's a __getitem__ method, it has a signatue of __getitem__(slef, index), then when we instantiate an object of this class, and call

for i in obj:
   print(i)

what method would python try to find and pass what argument?

Allen Huang
  • 55
  • 1
  • 9
  • Did you read https://stackoverflow.com/questions/926574/why-does-defining-getitem-on-a-class-make-it-iterable-in-python ? – azro Sep 04 '22 at 11:44
  • The code passes ints starting at 0, until your code (in getitem) raises an IndexError – azro Sep 04 '22 at 11:44
  • thanks, @zaro. I only know that __iter__ is the magic method for for in statement, now I get it – Allen Huang Sep 04 '22 at 14:35

1 Answers1

1

You can make a class iterable by implementing

  • __getitem, it'll receive ints starting at 0, your code needs to raise a IndexError to stop it

    class Foo:
        def __getitem__(self, item):
            if isinstance(item, int) and item > 10:
                raise IndexError
            return item * 2
    
  • __iter__ and __next__

    class Foo:
    
        def __init__(self):
            self.counter = 0
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if self.counter > 10:
                raise StopIteration
            result = self.counter * 2
            self.counter += 1
            return result
    

Both leads to same output

for i in Foo():
    print(i)

0
2
4
6
8
10
12
14
16
18
20
azro
  • 53,056
  • 7
  • 34
  • 70