What makes an iterator an iterator?
Steven D'Aprano
steve at REMOVEME.cybersource.com.au
Wed Apr 18 01:39:22 EDT 2007
I thought that an iterator was any object that follows the iterator
protocol, that is, it has a next() method and an __iter__() method.
But I'm having problems writing a class that acts as an iterator. I have:
class Parrot(object):
def __iter__(self):
return self
def __init__(self):
self.next = self._next()
def _next(self):
for word in "Norwegian Blue's have beautiful plumage!".split():
yield word
But this is what I get:
>>> P = Parrot()
>>> for word in P:
... print word
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: iter() returned non-iterator of type 'Parrot'
Why is my instance not an iterator?
But I can do this:
>>> for word in P.next:
... print word
...
Norwegian
Blue's
have
beautiful
plumage!
I find myself perplexed as to this behaviour.
--
Steven D'Aprano
More information about the Python-list
mailing list