Iteratoration question

andrew cooke andrew at acooke.org
Fri Apr 3 01:08:43 CEST 2009


grocery_stocker wrote:
>
>>
>> in summary: iterator is bound to one instance of "it", while some_func()
>> returns a new instance each time it is called.
>>
>> BUT
>>
>> while what you are doing is interesting, it is not the same as Python's
>> iterators, which use "yield" from a function and don't require storing a
>> value in a class.  look for "yield" in the python docs.  this comment
>> may
>> be irrelevant; i am just worried you are confusing the above (which
>> apart
>> from the mistake about instances is perfectly ok) and python's iterators
>> (which use next(), yield, etc).
>>
>
> Okay, one last question for now
>
> When I have the follow class
>
>>>> class it:
> ...    def __init__(self):
> ...        self.count = -1
> ...    def next(self):
> ...        self.count +=1
> ...        if self.count < 4:
> ...            return self.count
> ...        else:
> ...            raise StopIteraton
> ...
>
>
>
>>>> value = it()
>
> How comes I can;t go over 'value' like in the following
>
>>>> for x in value:
> ...     print x
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: iteration over non-sequence
>
> But yet, I can do...
>
>>>> value.next()
> 0
>>>> value.next()
> 1
>>>> value.next()
> 2
>>>> value.next()
> 3

replace return with yield and it might work.

i have to go eat, but if it doesn't read the python docs on iterators -
for example http://docs.python.org/reference/expressions.html#index-1825

andrew





More information about the Python-list mailing list