Why yield does not work in this construct?

I cannot understand why this yield construct gives me only one run in the for loop:

class myRange():
    def __init__(self, first, last):
        self.current = first - 1
        self.last = last

    def __iter__(self):
        self.current = self.current + 1
        if (self.current <= self.last):
            yield self.current


for n in myRange(1, 10):
    print(n)

which produces:

1

EDIT: Kind of weak question! I was tricked by the name of the __iter__ funciton…

>Solution :

Your __iter__ function needs to loop. As it is, it only yields once, so your loop only prints one value.

class myRange():
    def __init__(self, first, last):
        self.current = first
        self.last = last

    def __iter__(self):
        while self.current <= self.last:
            yield self.current
            self.current += 1

Leave a Reply