# 1, the nature of the generator is a iterator (iterator generator must be, but not necessarily the iterator generator) --- generator object
# 2, as long as the yield keyword is comprising a function generator, the generator performs the function generator to obtain a
# 3, yield only in the internal function, and can not be shared with return
# Generator function features:
1, call the generator function is not the time to perform, just generate a generator
2, each execution of the __next generator __ () returns a value, until the last one by a stop abnormality
# Example 1:
>>> def nihao():
print('a')
yield 1
print('b')
yield 2
print('c')
yield 3
print('d')
yield 4
Hello = NiHao >>> ()
>>> Next Hello .__ __ () # traverse of the generator is performed each time to yield a, each time to print a letter, the number of how many times the yield can be traversed
A
. 1
> Next Hello .__ __ >> ()
B
2
>>>
>>> Next Hello .__ __ ()
C
. 3
>>> Next Hello .__ __ ()
D
. 4
>>> Next Hello .__ __ ()
Traceback (MOST Recent Last Call):
File " <135 pyshell #> ", Line. 1, in <Module1>
Hello .__ Next __ ()
the StopIteration
>>>
# Loop through and used directly for consistent results
>>> for i in hello:
print(i)
a
1
b
2
c
3
d
4
Example 2:
# Monitor file file, any new print outputs yield can achieve read line by line, return can only be read once the function is over
def tail(filename):
f = open(filename)
while True:
line = f.readline()
if line.strip():
yield line.strip()
line = tail('file')
for i in line:
print(i)