# iterator example; uses Fibonacci numbers, so common in computer # science examples: f_n = f_{n-1} + f_{n-2}, with f_0 = f_1 = 1 class fibnum: def __init__(self): self.fn2 = 1 # "f_{n-2}" self.fn1 = 1 # "f_{n-1}" def next(self): # next() is the heart of any iterator # note the use of the following tuple to not only save lines of # code but also to insure that only the old values of self.fn1 and # self.fn2 are used in assigning the new values (self.fn1,self.fn2,oldfn2) = (self.fn1+self.fn2,self.fn1,self.fn2) return oldfn2 def __iter__(self): return self class fibnum20: def __init__(self): self.fn2 = 1 # "f_{n-2}" self.fn1 = 1 # "f_{n-1}" def next(self): (self.fn1,self.fn2,oldfn2) = (self.fn1+self.fn2,self.fn1,self.fn2) if oldfn2 > 20: raise StopIteration return oldfn2 def __iter__(self): return self