Iteratoration question

andrew cooke andrew at acooke.org
Thu Apr 2 18:29:49 EDT 2009


grocery_stocker wrote:
> Give the following code..
>
>>>> class it:
> ...    def __init__(self):
> ...        self.count = -1
> ...    def next(self):
> ...        self.count +=1
> ...        if self.count < 4:
> ...            return self.count
> ...        else:
> ...            raise StopIteration
> ...
>>>> def some_func():
> ...     return it()

this creates a new instance of "it", with a new count, every time the
function is called.

>>>> iterator = some_func()

this sets iterator to be an instance of "it".

>>>> iterator
> <__main__.it instance at 0xb7f482ac>

this is the single "it" instance that iterator is bound to.

>>>> some_func
> <function some_func at 0xb7f45e64>
>>>> some_func()
> <__main__.it instance at 0xb7f4862c>

this is another instance of "it" created when some_func was called.

> How come when I call some_func().next(), the counter doesn't get
> incremented?
>>>> some_func().next()
> 0

this creates yet another instance of "it" and calls next() on it.

>>>> some_func().next()
> 0

this creates another instance of "it" and calls next() on it.

>>>> some_func().next()
> 0

and another instance....

> But when I call iterator.next(), it does.
>>>> iterator.next()
> 0

this calls next() on the instance of "it" that iterator is bound to.

>>>> iterator.next()
> 1

this call next() again on the same instance of "it".

>>>> iterator.next()
> 2
>>>> iterator.next()
> 3

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).

andrew





More information about the Python-list mailing list