python中yield的用法详解——最简单,最清晰的解释

发布时间 2023-04-24 13:35:38作者: pu369com

原文在https://blog.csdn.net/mieleizhi0522/article/details/82142856

我也试着解释一下:如果函数foo()中中用了yield关键字,这个函数就变成了一个generator,yield相当于return ,当用next调用并执行到yield时会保存generator的状态并返回,等下次用next调用时会从yield的位置恢复状态,并继续执行

还是看代码吧:

def foo():
    print("generator starting...")
    i = 0
    while True:
        print("while...")
        res = yield i
        print("res:",res)
        i = i + 1
g = foo()  # foo()还未执行
print(next(g)) # next调用,foo()执行到yield就返回i的值,不会给res赋值,本行打印0
print("*"*20)
print(next(g)) #再次next调用,foo()从yield下一行继续,打印res值None,i增加1
print(next(g)) #多次next调用,会发现只是foo()中while部分循环执行,且res永远不会赋值
print(next(g))

  如果去掉foo()中的while,会提示error:StopIteration