[Tutor] a question about iterators

Christopher Spears cspears2002 at yahoo.com
Tue Jun 17 07:46:40 CEST 2008


I've been learning about how to implement an iterator in a class from Core Python Programming (2nd Edition).

>>> class AnyIter(object):
...     def __init__(self, data, safe=False):
...         self.safe = safe
...     self.iter = iter(data)
...
...     def __iter__(self):
...         return self
...
...     def next(self, howmany=1):
...         retval = []
...     for eachItem in range(howmany):
...         try:
...             retval.append(self.iter.next())
...         except StopIteration:
...             if self.safe:
...                 break
...             else:
...                 raise
...         return retval
...
>>>
>>> a = AnyIter(range(10))
>>> i = iter(a)
>>> for j in range(1,5):
...     print j, ':', i.next(j)
...
1 : [0]
2 : [1, 2]
3 : [3, 4, 5]
4 : [6, 7, 8, 9]

I am confused by this statement:
>>> i = iter(a)

Why do I need to turn 'a' into an iterator?  Didn't I already do this when I constructed the class?

As a test, I tried the following:

>>> for j in range(1,5):
...     print j, ':', a.next(j)
...
1 :
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
  File "<stdin>", line 13, in next
StopIteration
>>>

Why didn't that work?


      


More information about the Tutor mailing list