我慢慢地开始关注 Python 生成器。
虽然现在这不是现实生活中的问题,但我仍然想知道为什么我不能从函数中返回生成器。
当我用 定义函数时yield
,它充当生成器。但是,如果我在另一个函数中定义它并尝试返回它,我会得到一个普通函数,即不是带有next
方法的生成器。
换句话说,为什么give_gen()
下面代码中的方法不起作用?
#!/usr/bin/python
import time
def gen(d):
n = 0
while True:
n = n + d
time.sleep(0.5)
yield n
def give_gen(d):
def fn():
n = 0
while True:
n = n + d
time.sleep(0.5)
yield n
return fn
if __name__ == '__main__':
g = give_gen(3) # does not work
g = gen(3) # works well
while True:
print g.next()
# AttributeError: 'function' object has no attribute 'next'
# in case of give_gen
为什么我不能从函数中返回生成器?