Is there any Iterator type example?

Thomas Moore jsfrank.chen at msa.hinet.net
Wed Nov 16 06:01:37 EST 2005


Hi:

Thanks, it does help. Besides, I search the web and find several other
examples, too.
--Thomas

----- Original Message -----
From: "Fredrik Lundh" <fredrik at pythonware.com>
To: <python-list at python.org>
Sent: Wednesday, November 16, 2005 4:02 PM
Subject: Re: Is there any Iterator type example?


> Thomas Moore wrote:
>
> > But what I really want to know is how to use __iter()__ and next() in a
> > class with an example.
>
> here's a simple iterator class that iterators over itself once:
>
> class Iterator1:
>     def __init__(self, size=10):
>         self.count = 0
>         self.size = size
>     def __iter__(self):
>         return self
>     def next(self):
>         count = self.count + 1
>         if count >= self.size:
>             raise StopIteration
>         self.count = count
>         return count
>
> it = Iterator1()
> print it
> for i in it:
>     print i
> for i in it:
>     print i
>
> if you run this, you'll see that only the first for-statement will
actually
> print anything.  when you loop over the iterator again, it's already ex-
> hausted.
>
> here's a more general variant, where the Iterable class can be iterated
> over several times.  to do this, its __iter__ method uses a separate
helper
> class to do the actual iteration:
>
> class Iterable2:
>     def __init__(self, size=10):
>         self.size = size
>     def __iter__(self):
>         return Iterator2(self)
>
> class Iterator2:
>     def __init__(self, target):
>         self.target = target
>         self.count = 0
>     def __iter__(self):
>         return self
>     def next(self):
>         count = self.count + 1
>         if count >= self.target.size:
>             raise StopIteration
>         self.count = count
>         return count
>
> it = Iterable2()
> print it
> for i in it:
>     print i
> for i in it:
>     print i
>
> to get a better view of what happens when you run the code, try adding
> print statements to the __iter__ and next methods.
>
> hope this helps!
>
> </F>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>




More information about the Python-list mailing list