一般而言包含yield关键词的函数就是生成器函数,生成器函数最终返回的是一个生成器。
>>> def count_num():
... yield 1
... yield 2
... yield 3
... yield 4
... return
... num=count_num()
#
# 调用next()依次向下取值,yield类似return,中断流程,记录返回当前的值,
#一直往下执行,直到执行生成器函数中的return触发生成器对象抛出stopiteration异常,
# 再往下取值就为空了。
>>> next(num)
1
>>> next(num)
2
>>> next(num)
3
>>> next(num)
4
>>> next(num)
Traceback (most recent call last):
File "<input>", line 1, in <module>
StopIteration
def output_ab():
print("start flag")
yield "a"
print("continue flag")
yield "b"
print("end")
output=output_ab()
print(next(output))
start flag
a
print(next(output))
continue flag
b
print(next(output))
end
Traceback (most recent call last):
File "<input>", line 1, in <module>
StopIteration
def output_num():
for r in range(6):
yield r
num=output_num()
print(next(num))
0
print(next(num))
1
print(next(num))
2
print(next(num))
3
print(next(num))
4
print(next(num))
5
print(next(num))
Traceback (most recent call last):
File "<input>", line 1, in <module>
StopIteration
#生成器表达式
new_num=(x*x for x in output_num())
print(next(new_num))
0
print(next(new_num))
1
print(next(new_num))
4
print(next(new_num))
9
print(next(new_num))
16
print(next(new_num))
25
print(next(new_num))
Traceback (most recent call last):
File "<input>", line 1, in <module>
StopIteration