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?

3
  • Did you read stackoverflow.com/questions/926574/… ? Commented Sep 4, 2022 at 11:44
  • The code passes ints starting at 0, until your code (in getitem) raises an IndexError Commented Sep 4, 2022 at 11:44
  • thanks, @zaro. I only know that iter is the magic method for for in statement, now I get it Commented Sep 4, 2022 at 14:35

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.