...

/

A Fibonacci Iterator

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 = max
def __iter__(self): #③
self.a = 0
self.b = 1
return self
def __next__(self): #④
fib = self.a
if fib > self.max:
raise StopIteration #⑤
self.a, self.b = self.b, self.a + self.b
return 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. ...

Access this course and 1400+ top-rated courses and projects.