这一章节我们来讨论一下扩展生成器函数:send函数
回顾一下上一章节我们介绍yield的应用:
>>> def test(): for x in range(3): yield x >>> x=test() >>> next(x) 0 >>> next(x) 1
下面我先举例:
>>> def test(): for x in range(4): y=yield x print(y) >>> test() <generator object test at 0x01E69A58> >>> a=test() >>> next(a) 0 >>> a.send (99) 99 1 >>> a.send (88) 88 2 >>> a.send (5) 5 3 >>> a.send (6) 6 Traceback (most recent call last): File "<pyshell#35>", line 1, in <module> a.send (6) StopIteration
1.先把send里面的参数赋值给生成器函数yield x
2.然后再执行print(y)这一句
3.执行生成器函数
4.把控制器交还给函数
注意:第一句是不可以直接使用send,会报错
>>> def test(): for x in range(4): y=(yield x)+2 >>> a=test() >>> a.send (5) Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> a.send (5) TypeError: can't send non-None value to a just-started generator
>>> def test(): for x in range(4): y=(yield x)+2 print(y) >>> a=test() >>> next(a) 0 >>> a.send (5) 7 1 >>> a.send (10) 12 2
总结:这一章节讨论了生成器函数的方法send,并且解析send的执行步骤,还有介绍send需要注意的地方。
这一章节就说到这里,谢谢大家
------------------------------------------------------------------
点击跳转零基础学python-目录