定义好一个生成器之后,需要怎么启动?怎么唤醒?
def gen():
i = 0
while i < 5:
temp = yield i
print(temp)
i += 1
f=gen()
f.send(122)
上述代码运行,发现报错如下:
Traceback (most recent call last):
File "/home/itcast/Desktop/python_9/send_next.py", line 12, in <module>
f.send(122)
TypeError: can't send non-None value to a just-started generator
指明在未启动的生成器中不能使用send传递一个非空的值,也就是说不能用send(value)来启动一个生成器,那么如何解决呢?
方法1:
使用next()启动生成器之后再用send(value)唤醒并传递数据
def gen():
i = 0
while i < 5:
temp = yield i
print(temp)
i += 1
f=gen()
next(f)
f.send(122)
方法2:
使用send(None)来启动生成器之后再用send(value)唤醒并传递数据
def gen():
i = 0
while i < 5:
temp = yield i
print(temp)
i += 1
f=gen()
f.send(None)
f.send(122)