代码:函数
def addlist(alist): for i in alist: yield i + 1 alist = [1, 2, 3, 4] for x in addlist(alist): print(x)
结果:spa
2 3 4 5
代码:code
def h(): print('Wen Chuan') yield 5 print('Fighting!') c = h() c.__next__()# output:Wen Chuan c.__next__()#因为后面没有yield了,所以会拋出异常
结果:blog
Traceback (most recent call last): File "E:/PyCharmProject/test.py", line 23, in <module> c.__next__() StopIteration Wen Chuan Fighting!
其实next()和send()在必定意义上做用是类似的,区别是send()能够传递yield表达式的值进去,而next()不能传递特定的值,只能传递None进去。所以,咱们能够看作c.next() 和 c.send(None) 做用是同样的。
get
代码:io
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
结果:ast
Wen Chuan m:Fighting! r:12