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)

結果:spa

2
3
4
5

2. next()語句

代碼: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!

3. send(msg) 與 next()

  其實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
相關文章
相關標籤/搜索