What is the difference between normal function and generator function?
我试图理解以下方法,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | In [26]: def generator(): ....: print 'generator function hits' ....: for i in range(3): ....: yield i ....: In [27]: def normal(): ....: print 'normal function hits' ....: return range(3) ....: In [28]: gen = generator() In [29]: type(gen) Out[29]: generator In [30]: fun = normal() normal function hits In [31]: type(fun) Out[31]: list |
在这里,我对上述代码的研究,26是
因为在调用生成函数的
1 2 3 4 | >>> gen = generator() >>> next(gen) generator function hits 0 |
现在,在第二个
1 2 | >>> next(gen) 1 |
号
生成器函数在yield处停止,然后再次调用,它将从yield停止的位置恢复。