正常功能和发电机功能有什么区别? [英] What is the difference between normal function and generator function?

查看:52
本文介绍了正常功能和发电机功能有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解以下方法,

I am trying to understand the below methodology,

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

这是我根据上述代码进行的研究,当我将 generator()函数分配给gen变量时,26是 generator()函数,而27是 normal()函数没有看到任何类似 generator function hits 的打印消息,但是,如果我已将 normal()函数分配给fun变量,我就看到了类似 normal的打印消息功能点击.我的问题是为什么generator()函数未命中?

Here my research from the above code, 26 is the generator() function and 27 is the normal() function, when I have assigned generator() function to gen variable I haven't seen any print message like generator function hits, But if I have assigned the normal() function to fun variable, I have seen the print message like normal function hits. My question is why generator() function not hit ?

推荐答案

因为只有在调用 next 时,生成器函数的主体才会被执行.

Because a generator function's body is not executed until you call next on it.

>>> gen = generator()
>>> next(gen)
generator function hits
0

现在,在第二个 next()调用中,生成器将从停止的位置再次运行:

Now on the second next() call the generator will run again from where it left off:

>>> next(gen)
1

这篇关于正常功能和发电机功能有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆