A Fibonacci Iterator
We'll cover the following...
Now you’re ready to learn how to build an iterator. An iterator is just a class that defines an __iter__()
method.
Press + to interact
class Fib: #①def __init__(self, max): #②self.max = maxdef __iter__(self): #③self.a = 0self.b = 1return selfdef __next__(self): #④fib = self.aif fib > self.max:raise StopIteration #⑤self.a, self.b = self.b, self.a + self.breturn fib #⑥
① To build an iterator from scratch, Fib
needs to be a class, not a function.
② “Calling” Fib(max)
is really creating an instance of this class and calling its __init__()
method with max
. The __init__()
method saves the maximum value as an instance variable so other methods can refer to it later.
③ The __iter__(
) method is called whenever someone calls iter(fib)
. (As you’ll see in a minute, a for
loop will call this automatically, but you can also call it yourself manually.) After performing beginning-of-iteration initialization (in this case, resetting self.a
and self.b
, our two counters), the ...