我见过一段 Python 3 代码:
def gen():
try:
while True:
yield 1
finally:
print("stop")
print(next(gen()))
运行之后,我一开始以为输出应该是:
1
但实际上结果是:
stop
1
这怎么会发生?幕后发生了什么?
如果我运行 for i in gen(): print(i)
,将会出现一个无限循环,这正是我所期望的。这里的for
和next
有什么区别?
最佳答案
finally 子句正在生成器对象的垃圾回收中执行。
考虑以下两种情况:
def gen():
try:
while True:
yield 1
finally:
print("stop")
g1 = gen(); print('first time')
print(next(g1))
g2 = gen(); print('second time') # no stop will be printed because we haven't hit the finally clause yet
def gen():
try:
while True:
yield 1
finally:
print("stop")
g = gen(); print('first time')
print(next(g))
g = gen(); print('second time') # stop will be printed when the first object g was assigned to is garbage collected
关于python - 最后在 Python 3 生成器中尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56062909/