Gra*_*ead 5 python iterator yield control-flow python-3.x
如果运行以下代码片段,它将忽略第 2 行的“print”和第 3 行的“exit”。但是,如果您注释掉第4 行中已经无法访问的“yield”,则第 2 行和第 3 行将正常执行。
这让我认为 Python (3.5.2) 在函数中的任何位置寻找“yield”,如果找到了,即使是无法访问的,也不会执行任何操作,直到在返回的迭代器上调用 next() 为止。到目前为止,我的印象是该函数将正常执行直到达到收益,此时它将开始像迭代器一样运行。
def func():
print("> Why doesn't this line print?")
exit() # Within this function, nothing should matter after this point. The program should exit
yield "> The exit line above will exit ONLY if you comment out this line."
x = func()
print(x)
Run Code Online (Sandbox Code Playgroud)
这对其他人来说看起来很奇怪吗?有人有一些见解可以在这里分享吗?
| 归档时间: |
|
| 查看次数: |
199 次 |
| 最近记录: |