最简单明了的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

原文地址:https://www.cnblogs.com/bbjs/p/13565249.html