我见过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有什么不同?
发布于 2019-05-09 23:57:52
正在对生成器对象的垃圾回收执行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 yetdef 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发布于 2019-05-09 23:59:03
当生成器关闭时,循环终止,如果您不保存对它的引用,则会自动发生这种情况。一旦发生这种情况,try语句就会保证在生成器对象被垃圾回收之前执行finally块。比较:
>>> next(gen())
stop
1使用
>>> x = gen()
>>> next(x)
1https://stackoverflow.com/questions/56062909
复制相似问题