how to customize implementation of the for in statement
Question:
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?
Answers:
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
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?
You can make a class iterable by implementing
-
__getitem
, it’ll receive ints starting at 0, your code needs to raise aIndexError
to stop itclass 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