首页 > 解决方案 > 生成器表达式中的 close()

问题描述

close在使用生成器/生成器表达式时曾经使用过,还是主要是内部方法?例如:

def odd_less_than_six():
    n = 1
    while n < 6:
        yield n
        n += 2

... 
>>> f=odd_less_than_six()
>>> next(f)
1
>>> next(f)
3
>>> next(f)
5
>>> next(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

或手动:

>>> f=odd_less_than_six()
>>> next(f)
1
>>> f.close()
>>> next(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

close在生成器方法中何时手动调用是否有真实的用例?

标签: pythongenerator

解决方案


推荐阅读