Is there any Iterator type example?

Fredrik Lundh fredrik at pythonware.com
Wed Nov 16 03:02:18 EST 2005


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> 






More information about the Python-list mailing list