生成器是一次生成一个值的特殊类型函数。可以将其视为可恢复函数。

对一个函数来说,如果需要记住一些执行状态。那对于一个普通函数,状态一定保存在函数体之外,也就是要用到全局变量(或静态全局变量),破坏了封装性。而对于一个类的成员函数,则通常将状态保存在类的成员变量中,封装性很好。

生成器吸取两种方式的长处, 在普通函数的简捷形式的基础之上,又不破坏封装性,并达到了记录状态的目的。

简单的说就是在函数的执行过程中,yield语句会把你需要的值返回给调用生成器的地方,然后退出函数,下一次调用生成器函数的时候又从上次中断的地方开始执行,而生成器内的所有变量参数都会被保存下来供下一次使用。

与一般的函数不同的是,在调用生成器函数时,其函数体并没有被执行。只有执行next()的时候,函数体才真正开始执行

看下面一个简单的例子:for i in range(N):

yield i ** 2

if __name__ == '__main__':

G = generatorSquares(5)

while True:

try:

print(G.__next__())

except StopIteration:

break

例子中的generatorSquares中含有yield,它即是一个生成器函数,运行以上示例结果如下:

0

1

4

9

16

由此可以看出,generatorSquares可以记录运行的状态,当第一次调用时,generatorSquares中i为1,并在yield处暂停返回02并记录状态。待第二次调用时恢复之前的状态,i=2,之后yield 12,是不是很有趣呢?再然后以此类推...最后在到达末尾时,会抛出StopIteration异常以便停止迭代。

生成器可以拿来做什么呢?以下是引用的stackoverflow上的一段回答:

Generators give you lazy evaluation. You use them by iterating over them, either explicitly with 'for' or implicitly by passing it to any function or construct that iterates. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one-by-one, and the generator function is paused until the next item is requested.

Generators are good for calculating large sets of results (in particular calculations involving loops themselves) where you don't know if you are going to need all results, or where you don't want to allocate the memory for all results at the same time. Or for situations where the generator usesanothergenerator, or consumes some other resource, and it's more convenient if that happened as late as possible.

Another use for generators (that is really the same) is to replace callbacks with iteration. In some situations you want a function to do a lot of work and occasionally report back to the caller. Traditionally you'd use a callback function for this. You pass this callback to the work-function and it would periodically call this callback. The generator approach is that the work-function (now a generator) knows nothing about the callback, and merely yields whenever it wants to report something. The caller, instead of writing a separate callback and passing that to the work-function, does all the reporting work in a little 'for' loop around the generator.

For example, say you wrote a 'filesystem search' program. You could perform the search in its entirety, collect the results and then display them one at a time. All of the results would have to be collected before you showed the first, and all of the results would be in memory at the same time. Or you could display the results while you find them, which would be more memory efficient and much friendlier towards the user. The latter could be done by passing the result-printing function to the filesystem-search function, or it could be done by just making the search function a generator and iterating over the result.

python 生成器_Python生成器相关推荐

  1. 用python编写图片生成器_python生成器

    生成器 一.生成器 定义: 生成器与迭代器看成是一种.生成器的本质就是迭代器. 唯一的区别: 生成器是自己用python写代码构建的数据结构.迭代器都是(系统)提供的,或者转化而来的 获取生成器的三种 ...

  2. python做投标生成器_Python 生成器(generator)详细总结+示例

    简介 生成器(generator)是一种返回一个值的迭代器,每次从该迭代器取下一个值. 生成器有两种表示: 生成器表达式 生成器函数 生成器函数还包括一下内容: 通用生成器 协程生成器 委托生成器 子 ...

  3. python 生成器_Python生成器中的GeneratorExit

    我写了一个关于Python生成器的测试程序.但是我得到了一个不期望的错误.我不知道如何解释它.我来告诉你代码: def countdown(n): logging.debug("Counti ...

  4. python 生成器_python 生成器 - 刘江的python教程

    生成器 阅读: 13136 评论:7 前面我们已经好几次提到了生成器的概念.这里对其简要介绍一下. 有时候,序列或集合内的元素的个数非常巨大,如果全制造出来并放入内存,对计算机的压力是非常大的.比如, ...

  5. python生成器_Python生成器

    python生成器 We will look into python generator today. In our previous lesson we have learnt about pyth ...

  6. python做投标生成器_Python生成器(Generator)详解

    通过列表生成式,我们可以直接创建一个列表.但是,受到内存限制,列表容量肯定是有限的.而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素 ...

  7. python 生成器_Python生成器的用法

    生成器类似于列表,其输出为一个线性的数据链.但生成器并不是一次将所有的数据都生成,而是仅在需要时生成一个数据. 下面的例子定义一个最简单的生成器: >>> generator_Dem ...

  8. python经济_python生成器——懒到欠揍,但很经济

    生成器的特点是工作到一半,就会停下来看别人干活直至有人踢它屁股,这时它才继续往下干活.实现这一功能的精髓要用到yield. 生成器是一种特殊的迭代器,因此我们先来了解一下什么是迭代器.我们都知道著名的 ...

  9. python迭代器与生成器_Python的迭代器和生成器

    一 概要 在了解Python的数据结构时,容器(container).可迭代对象(iterable).迭代器(iterator).生成器(generator).列表/集合/字典推导式(list,set ...

  10. python生成器推导式的结果是一个什么类似于对象_python 生成器和推导式

    一. 生成器 什么是生成器. 生成器实质就是迭代器. 在python中有三种方式来获取生成器: 1. 通过生成器函数 2. 通过各种推导式来实现生成器 3. 通过数据的转换也可以获取生成器 首先, 我 ...

最新文章

  1. Resin介绍及其使用配置
  2. 3模型大小_分布式训练中数据并行远远不够,「模型并行+数据并行」才是王道...
  3. html5 游戏图片预加载,前端实现图片(img)预加载
  4. HRBUST 2072 树上求最大异或路径值
  5. 1.2 什么是神经网络-深度学习第一课《神经网络与深度学习》-Stanford吴恩达教授
  6. 雅思听力的词语练习打字!!!
  7. java ssh 和mvc_[转]JAVA三大框架SSH和MVC
  8. LINQ 学习路程 -- 查询语法 LINQ Query Syntax
  9. [Unity] GameFramework 学习记录 3
  10. OCX控件注册相关(检查是否注册,注册,反注册)
  11. 一加7是什么协议_刘作虎“拔钉”成功:大量一加5、一加3用户入手一加8T
  12. 统计自然语言处理梳理一:分词、命名实体识别、词性标注
  13. Window下完全卸载MySQL教程
  14. Python实现简单人脸识别
  15. Office更新了那么多代,哪个版本好看呢?
  16. Asp.Net Core3.1-集成Hangfire
  17. 如何提高逻辑思维能力
  18. EventBus底层实现原理
  19. 手机通讯原理的工作原理
  20. 强大的虚拟机软件vmware图文使用教程

热门文章

  1. 即插即用 | 超越CBAM,全新注意力机制,GAM不计成本提高精度(附Pytorch实现)...
  2. 深度学习中的Attention总结
  3. 京西古道,王平到圈门的穿越
  4. git分支创建与合并
  5. 前端小知识-html5
  6. 爬虫协程比线程爬取速度更快?
  7. 14.6.4 Configuring the Memory Allocator for InnoDB 配置InnoDB 内存分配器
  8. MyEclipse中VSS的使用详解
  9. 【生活相关】二(2014年新年畅想)
  10. 【python|opencv】读取/保存图片,路径含有中文问题解放方案(opencv 无法读取/保存图片)