pu369com

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

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

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

还是看代码吧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

posted on   pu369com  阅读(106)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示