Iteratoration question

Rhodri James rhodri at wildebst.demon.co.uk
Thu Apr 2 18:33:16 EDT 2009


On Thu, 02 Apr 2009 23:14:49 +0100, grocery_stocker <cdalten at gmail.com>  
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()
> ...
>>>> iterator = some_func()
>>>> iterator
> <__main__.it instance at 0xb7f482ac>
>>>> some_func
> <function some_func at 0xb7f45e64>
>>>> some_func()
> <__main__.it instance at 0xb7f4862c>
>
> How come when I call some_func().next(), the counter doesn't get
> incremented?
>>>> some_func().next()
> 0
>>>> some_func().next()
> 0
>>>> some_func().next()
> 0

Here, you are creating an instance of the class "it", incrementing
and returning that instance's counter, then throwing the instance away.

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

Here you already have a single instance, and you don't throw it away
after incrementing its counter.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list