-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfib_iterator.py
More file actions
24 lines (22 loc) · 876 Bytes
/
fib_iterator.py
File metadata and controls
24 lines (22 loc) · 876 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Fib:
''' Iterator which will return fib values'''
# Usually capitalized to differentiate from Python built-ins
def __init__(self, maximum):
self.maximum = maximum
# self is not a reserved word in Python
# But, it's a bad idea to use anything else here.
# Self refers to the instance of the class called
# Don't introduce new variables outside of __init__
# Need object consistency - it should never enter a state that doesn't make sense
def __iter__(self):
self.a = 0
self.b = 1
return self
# Necessary anytime someonecalls iter(Fib)
def __next__(self):
fib = self.a
if fib > self.max:
raise StopIteration # Stopping conditions.
self.a, self.b = self.b, self.a + self.b
return fib # Need to use return, not yield. Yield is for generators
# Necessary anytime someone calls next(Fib)