[Tutor] _next
Roel Schroeven
rschroev_nospam_ml at fastmail.fm
Thu May 25 10:16:43 CEST 2006
Christopher Spears schreef:
> How does this script work?
>
> #!/usr/bin/python
>
> class IteratorExample:
> def __init__(self, s):
> self.s = s
> self.next = self._next().next
> self.exhausted = 0
> def _next(self):
> if not self.exhausted:
> flag = 0
> for x in self.s:
> if flag:
> flag = 0
> yield x
> else:
> flag = 1
> self.exhausted = 1
> def __iter__(self):
> return self._next()
I always use generator functions like this to achieve the same effect:
def IteratorExample():
flag = 0
for x in s:
if flag:
flag = 0
yield x
else:
flag = 1
Much less boilerplate and behind-the-scenes bookkeeping, so it's easier
to type and understand. Result is the same:
>>> a = IteratorExample('edcba')
>>> for x in a:
print x
d
b
>>> a = IteratorExample('edcba')
>>> print a.next()
d
>>> print a.next()
b
>>> print a.next()
Traceback (most recent call last):
File "<pyshell#82>", line 1, in -toplevel-
print a.next()
StopIteration
--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton
Roel Schroeven
More information about the Tutor
mailing list