[Tutor] Iterators and Generators...
Neil Schemenauer
nas-pytut at python.ca
Wed Aug 13 10:24:26 EDT 2003
Karl Pfl?sterer wrote:
> You never called your next() method (and you have a typo); I underlined
> both in your example.
>
> So the correct code would be:
>
> class list_iterator:
> def __init__(self, a_list):
> self.a_list = a_list
>
> def __iter__(self):
> return self.next()
>
> def next(self):
> for i in self.a_list:
> yield i
> raise StopIteration
Yikes. There's no need to explicitly raise StopIteration. Also, the
'next' method could be called anything. Don't get confused that the
name is somehow special. For example, the following code does exactly
the same thing:
class list_iterator:
def __init__(self, a_list):
self.a_list = a_list
def __iter__(self):
return self.pumpkin()
def pumpkin(self):
for i in self.a_list:
yield i
Furthermore, you don't need the extra method if you put the yield loop
in the __iter__ method.
Neil
More information about the Tutor
mailing list