Python生成器中的yield、send、next详解

真的,技术博客不能乱写,看了一个多小时的网上所谓的详解,还是一头雾水,只能自己去翻书,好了,让我给大家一次搞清楚Python中的send和next。

In [1]: import types

In [2]: def gen():
   ...:     print('enter')
   ...:     a = yield 1 # State A
   ...:     print('next')
   ...:     print(a or 'a')
   ...:     b = yield 2 # State B
   ...:     print(b or 'b')
   ...:     print('next again')
   ...:

In [3]: g = gen() #生成器赋给g

In [4]: print(type(g)) #输出g的类型
<class 'generator'>

In [5]: print('g isinstance types.GeneratorType: '+str(isinstance(g,typ
   ...: es.GeneratorType))) #判断其是否是生成器
g isinstance types.GeneratorType: True

In [6]: print(next(g)) #运行到State A 结束,并挂起A进程,但未进行赋值操作
enter
1

In [7]: i =0

In [8]: while(i>=0):
   ...:     i+=1
   ...:     print('i:'+str(i))
   ...:     try:
   ...:         print(g.send('x')) #A进程继续,将x传入yield中(替换1),从赋值操作开始继续执行(即yield的下一步操作),直至State B,yield 2 执行完毕,State B的赋值操作同样未进行。
   ...:     except StopIteration: #while语句第三次执行,无yield语句,程序报错
   ...:         break
   ...:
i:1
next
x
2
i:2
x
next again

In [9]: print('此处是分界线-------------')
此处是分界线-------------

In [10]: g2 = gen()

In [11]: print(type(g2))
<class 'generator'>

In [12]: for x in g2: #这里的A、B赋值操作从未执行(值均被返回),均为None
    ...:     print(x)
    ...:
enter
1
next
a
2
b
next again
发布了101 篇原创文章 · 获赞 46 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_40539952/article/details/103880618