[Tutor] __getitem__() and for loops
Gonçalo Rodrigues
op73418 at mail.telepac.pt
Fri Oct 10 16:52:12 EDT 2003
On Fri, 10 Oct 2003 16:39:46 -0400, you wrote:
>Quick question:
>
>Is a for loop actually calling __getitem__() behind the scenes, and passing in the current index of the range of the for loop?
>
Let us test:
>>> class Test(object):
... def __init__(self, n):
... self.n = int(n)
... def __getitem__(self, i):
... if 0 <= i < self.n:
... return i
... else:
... raise IndexError
...
>>> t = Test(4)
>>> for i in t:
... print i
...
0
1
2
3
So it seems...
Python looks first for __iter__ then tries __getitem__ -- also for
backwards compatibility. Before the iterator protocol (< 2.2) coding a
__getitem__ was the standard way to make classes cooperate with
for-loops.
With my best regards,
G. Rodrigues
More information about the Tutor
mailing list