1. 程式人生 > 實用技巧 >最簡單明瞭的yield from解釋

最簡單明瞭的yield from解釋

def one():
    print('one start')
    res = yield from two()
    print('function get res: ', res)
    return 'one' + res


def two():
    print('two start')
    res = yield from three()
    print(">>> two1")
    return res


def three():
    print(">>> three1")
    yield 1
    print
(">>> three2") return 'three' if __name__ == '__main__': gen = one() print(">>> 1") send_1 = gen.send(None) print(">>> 2") print(send_1) print(">>> 3") send_2 = gen.send(None) print(">>> 4") print(send_2) print
(">>> 5")

執行結果:

>>> 1
one start
two start
>>> three1
>>> 2
1
>>> 3
>>> three2
>>> two1
function get res:  three
Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/1.py", line 29, in <module>
    send_2 = gen.send(None)
StopIteration: onethree
>>>

不要把yield from 想的太複雜,就把yield from呼叫看作是普通函式呼叫來看程式碼。一旦遇到yield會返回。再次send,特點和生成器一樣。

1、當send裡面的函式先遇到的是yield from語句,那麼會繼續往下呼叫,直到遇到yield會暫停並返回給呼叫方。

main->one()->two()->three->遇到yield- >main

2、遇到yield語句,會直接返回到send語句所在函式, 也就是send_1 = gen.send(None),send_1 賦值為 three()中的 yield 1

3、再次呼叫send語句,就會變成1的反向呼叫,從yield暫停的地方 three() 函式的 yield 1下面開始執行

three()->two()->one->main

4、yield from後面的函式返回值會得到,賦值給左值

three()的返回值會給two()的res,two()的返回值會給one()

轉載至https://www.jianshu.com/p/01d8100c2b41