Skip to content

Commit 6ce10db

Browse files
committed
add yield tutorial
1 parent e16301c commit 6ce10db

File tree

5 files changed

+149
-8
lines changed

5 files changed

+149
-8
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ Python Notes 學習筆記 📝
8888

8989
[__iter__tutorial](https://github.com/twtrubiks/python-notes/blob/master/__iter__tutorial.py) - `__iter__` tutorial
9090

91+
[yield_tutorial.py](yield_tutorial.py)- yield tutorial
92+
9193
[__str__tutorial.py](https://github.com/twtrubiks/python-notes/blob/master/__str__tutorial.py) - `__str__` tutorial
9294

9395
[strtobool_tutorial.py](https://github.com/twtrubiks/python-notes/blob/master/strtobool_tutorial.py) - strtobool
@@ -110,7 +112,7 @@ Python Notes 學習筆記 📝
110112

111113
[configparser_tutorial](https://github.com/twtrubiks/python-notes/blob/master/configparser_tutorial) - ConfigParser tutorial,可參考 [https://docs.python.org/3/library/configparser.html](https://docs.python.org/3/library/configparser.html)
112114

113-
[_len_tutorial.py](https://github.com/twtrubiks/python-notes/blob/master/_len_tutorial.py) - _len_tutorial
115+
[__len__tutorial.py](https://github.com/twtrubiks/python-notes/blob/master/__len__tutorial.py) - `__len__` tutorial
114116

115117
[decimal_tutorial.py](https://github.com/twtrubiks/python-notes/blob/master/decimal_tutorial.py) - decimal tutorial
116118

File renamed without changes.

iter_tutorial.py

Lines changed: 63 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
1+
from collections.abc import Iterable, Iterator
2+
13

24
# The iter() method returns an iterator for the given object.
35

46
# The syntax of iter() method is
57
# iter(object[, sentinel])
68

79

10+
# The iterator protocol
11+
# Any class that provides an __iter__ method is iterable;
12+
# that method must return an Iterator instance that will cover
13+
# all the elements in that class.
14+
# Since an iterator is already looping over elements,
15+
# its __iter__ function traditionally return itself.
16+
17+
# Iterable - __iter__ (for in), iter(Iterable) -> Iterator
18+
# Iterator - __next__ + __iter__
19+
820
class PrintNumber:
921
def __init__(self, max_number):
1022
self.max_number = max_number
@@ -20,19 +32,63 @@ def __next__(self):
2032
return self.num
2133

2234

23-
if __name__ == "__main__":
24-
printNum = PrintNumber(3)
35+
def example_1():
36+
print_mum = PrintNumber(3)
2537

26-
printNumIter = iter(printNum)
38+
print_mum_iter = iter(print_mum)
2739

2840
# prints '1'
29-
print(next(printNumIter))
41+
print(next(print_mum_iter))
3042

3143
# prints '2'
32-
print(next(printNumIter))
44+
print(next(print_mum_iter))
3345

3446
# prints '3'
35-
print(next(printNumIter))
47+
print(next(print_mum_iter))
3648

3749
# raises StopIteration
38-
print(next(printNumIter))
50+
print(next(print_mum_iter))
51+
52+
53+
class CapitalIterable:
54+
def __init__(self, string):
55+
self.string = string
56+
57+
def __iter__(self):
58+
return CapitalIterator(self.string)
59+
60+
61+
class CapitalIterator:
62+
def __init__(self, string):
63+
self.words = [w.capitalize() for w in string.split()]
64+
self.index = 0
65+
66+
def __next__(self):
67+
if self.index == len(self.words):
68+
raise StopIteration()
69+
word = self.words[self.index]
70+
self.index += 1
71+
return word
72+
73+
def __iter__(self):
74+
return self
75+
76+
77+
def example_2():
78+
iterable = CapitalIterable('the aa bb cc dd')
79+
print('isinstance(iterable,Iterable):', isinstance(iterable, Iterable))
80+
iterator = iter(iterable)
81+
print('isinstance(iterator,Iterator):', isinstance(iterator, Iterator))
82+
while True:
83+
try:
84+
print(next(iterator))
85+
except StopIteration:
86+
break
87+
88+
for i in iterable:
89+
print(i)
90+
91+
92+
if __name__ == "__main__":
93+
example_1()
94+
# example_2()

set_tutorial.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
ref. https://docs.python.org/3/tutorial/datastructures.html#sets
44
A set is an unordered collection with no duplicate elements
55
'''
6+
# set_seqs = {'a', 'b'} # set
7+
# dict_seqs = {} # dict
68
set_seqs = set()
79
set_seqs.add('test1')
810
set_seqs.add('test2')

yield_tutorial.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# yield occurs and the generator pauses.
2+
def common_func(max_number):
3+
print("create counter")
4+
counter = 0
5+
while counter < max_number:
6+
print(counter)
7+
print('counter +1')
8+
counter += 1
9+
10+
11+
def yield_func(max_number):
12+
print("create counter")
13+
counter = 0
14+
while counter < max_number:
15+
yield counter
16+
print('counter +1')
17+
counter += 1
18+
19+
20+
def example_1():
21+
num = yield_func(5)
22+
print(next(num))
23+
# print(next(num))
24+
# print(next(num))
25+
for n in num:
26+
print('n:', n)
27+
28+
29+
def yield_step():
30+
print('step 1')
31+
yield 1
32+
print('step 2')
33+
yield 2
34+
print('step 3')
35+
yield 3
36+
37+
38+
def example_2():
39+
test = yield_step()
40+
print(next(test))
41+
print(next(test))
42+
43+
44+
def return_list():
45+
return [
46+
i for i in range(5)
47+
]
48+
49+
50+
def return_yield():
51+
yield from (
52+
i
53+
for i in range(5)
54+
)
55+
56+
57+
def example_3():
58+
# yield only traversing once
59+
common_var = return_list()
60+
yield_var = return_yield()
61+
print('c1 in common_var')
62+
for c1 in common_var:
63+
print('c1:', c1)
64+
65+
print('y1 in yield_var')
66+
for y1 in yield_var:
67+
print('y1:', y1)
68+
69+
print('c2 in common_var')
70+
for c2 in common_var:
71+
print('c2:', c2)
72+
73+
print('y2 in yield_var') # not show
74+
for y2 in yield_var:
75+
print('y2:', y2)
76+
77+
78+
if __name__ == "__main__":
79+
example_1()
80+
# example_2()
81+
# example_3()

0 commit comments

Comments
 (0)