-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathiterator_example.py
75 lines (61 loc) · 1.31 KB
/
iterator_example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def main():
"""
>>> array = range(0, 5)
>>> iterator = iter(array)
>>> for item in iterator:
... print(item, end='')
01234
>>> iterator = iter(array)
>>> next(iterator)
0
>>> next(iterator)
1
>>> next(iterator)
2
>>> next(iterator)
3
>>> next(iterator)
4
>>> next(iterator)
Traceback (most recent call last):
...
StopIteration
"""
class Counter:
"""
>>> counter = Counter(5)
>>> iterator = iter(counter)
>>> for item in iterator:
... print(item)
1
2
3
4
5
"""
def __init__(self, count):
self.count = count
def __iter__(self):
self.num = 1
return self
def __next__(self):
if self.num <= self.count:
temp = self.num
self.num += 1
return temp
else:
raise StopIteration
class InfiniteCounter:
def __init__(self):
self.num = 0
def __iter__(self):
return self
def __next__(self):
self.num += 1
return self.num
if __name__ == "__main__":
from doctest import testmod
testmod()
# counter = InfiniteCounter()
# for item in iter(counter):
# print(item)