[Tutor] __iter__
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Tue Jan 17 19:33:21 CET 2006
> Where/how/when is 'def next(self(:' called?
The 'for' loop statement does this internally when it marches across an
iterable thing. We can write something something like this:
######################
for item in thing:
print item
######################
Python is doing something like this behind the scenes:
######################
iterable = iter(thing)
try:
while True:
item = iterable.next()
print item
except StopIteration:
pass
######################
The for loop is the one that's calling next() repeatedly on its iterable.
We can manually call next() ourselves, just to see what happens:
######
>>> names = ['homer', 'marge', 'sideshow bob']
>>> iterable = iter(names)
>>> iterable
<listiterator object at 0x6fdf0>
>>>
>>>
>>> iterable.next()
'homer'
>>> iterable.next()
'marge'
>>> iterable.next()
'sideshow bob'
>>> iterable.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
######
Does this make sense?
More information about the Tutor
mailing list