yield解析
1.yield可以用来为一个函数返回值塞数据
代码:
def addlist(alist): for i in alist: yield i + 1 alist = [1, 2, 3, 4] for x in addlist(alist): print(x)
结果:
2 3 4 5
2. next()语句
代码:
def h(): print('Wen Chuan') yield 5 print('Fighting!') c = h() c.__next__()# output:Wen Chuan c.__next__()#由于后面没有yield了,因此会拋出异常
结果:
Traceback (most recent call last): File "E:/PyCharmProject/test.py", line 23, in <module> c.__next__() StopIteration Wen Chuan Fighting!
3. send(msg) 与 next()
其实next()和send()在一定意义上作用是相似的,区别是send()可以传递yield表达式的值进去,而next()不能传递特定的值,只能传递None进去。因此,我们可以看做c.next() 和 c.send(None) 作用是一样的。
代码:
def h(): print('Wen Chuan') m = yield 5 # Fighting! print ('m:%s'%m) d = yield 12 print ('We are together!') c = h() c.__next__() #相当于c.send(None) output:Wen Chuan r=c.send('Fighting!') #(yield 5)表达式被赋予了'Fighting!' print('r:%d'%r)#返回值为yield 12
结果:
Wen Chuan m:Fighting! r:12