YumTum
YumTum

Reputation: 389

Looping over Iterator

Sorry if this is a silly question, but I could not make my mind up how it could work.

I defined an iterator which has a structure like that (it is a bit more complicated, but the model will do the job):

class MyIterator ():

    def __init__(self):
        print ('nothing happening here')

    def __iter__ (self):
        self.a_list=[x for x in range (10)]
        for y in a_list:
            print(y)


    def __next__ (self):
        self.a_list = [x+1 for x in self.a_list]
        for y in a_list:
            print (y)

But how can I loop over it? Do I always have to call the methods manually? Or am I simply using the wrong tool?

Upvotes: 2

Views: 107

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 601609

One of the problems is that you are mixing two concepts: And iterable defines an __iter__() method that returns an iterator, but no __next__() method. An iterator in turn defines a __next__() method, and a trivial __iter__() implementation that returns self. Something like this:

class Iterable(object):
    def __iter__(self):
        return Iterator()

class Iterator(object):
    def __init__(self):
        self.i = 0
    def __iter__(self):
        return self
    def __next__(self):
        result = self.i
        self.i += 1
        return result

An alternative is to define the __iter__() method of the iterable as a generator function:

class Iterable(object):
    def __iter__(self):
        i = 0
        while True:
            yield i
            i += 1

Upvotes: 7

Related Questions