Python2 生成器 简介
1.
A generator: provide a kind of function that can return an intermediate result ("the next value") to its caller, but maintaining the function's local state so that the function can be resumed again right where it left off.
A very simple example:
def fib():
a, b = 0, 1
while 1:
yield b
a, b = b, a+b
When fib() is first invoked, it sets a to 0 and b to 1, then yields b back to its caller. The caller sees 1. When fib is resumed, from its point of view the yield statement is really the same as, say, a print statement: fib continues after the yield with all local state intact. a and b then become 1 and 1, and fib loops back to the yield, yielding 1 to its invoker. And so on. From fib's point of view it's just delivering a sequence of results. But from its caller's point of view, the fib invocation is an iterable object that can be resumed at will.
The yield statement may only be used inside functions. A function that contains a yield statement is called a generator function.
When a generator function is called, the actual arguments are bound to function-local formal argument names in the usual way, but no code in the body of the function is executed. Instead a generator-iterator object is returned; this conforms to the iterator protocol, so in particular can be used in for-loops in a natural way.
Each time the .next() method of a generator-iterator is invoked, the code in the body of the generator-function is executed until a yield or return statement (see below) is encountered, or until the end of the body is reached.
If a yield statement is encountered, the state of the function is frozen, and the value of expression_list is returned to .next()'s caller. By "frozen" we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack: enough information is saved so that the next time .next() is invoked, the function can proceed exactly as if the yield statement were just another external call.
Note that an expression_list is not allowed on return statements in the body of a generator.
When a return statement is encountered, control proceeds as in any function return, executing the appropriate finally clauses (if any exist). Then a StopIteration exception is raised, signalling that the iterator is exhausted. A StopIteration exception is also raised if control flows off the end of the generator without an explicit return.
2: send
A new method for generator-iterators is proposed, called send(). It takes exactly one argument, which is the value that should be sent in to the generator. Calling send(None) is exactly equivalent to calling a generator's next() method. Calling send() with any other value is the same, except that the value produced by the generator's current yield expression will be different.
Because generator-iterators begin execution at the top of the generator's function body, there is no yield expression to receive a value when the generator has just been created. Therefore, calling send() with a non-None argument is prohibited when the generator iterator has just started, and a TypeError is raised if this occurs (presumably due to a logic error of some kind). Thus, before you can communicate with a coroutine you must first call next() or send(None) to advance its execution to the first yield expression.
The yield-statement will be allowed to be used on the right-hand side of an assignment; in that case it is referred to as yield-expression. The value of this yield-expression is None unless send() was called with a non-None argument; see below.
Note that a yield-statement or yield-expression without an expression is now legal. This makes sense: when the information flow in the next() call is reversed, it should be possible to yield without passing an explicit value (yield is of course equivalent to yield None).
When send(value) is called, the yield-expression that it resumes will return the passed-in value. When next() is called, the resumed yield-expression will return None. If the yield-expression is a yield-statement, this returned value is ignored, similar to ignoring the value returned by a function call used as a statement.
3: Exceptions and Cleanup
throw(type, value=None, traceback=None)
g.throw(type, value, traceback) causes the specified exception to be thrown at the point where the generator g is currently suspended (i.e. at a yield-statement, or at the start of its function body if next() has not been called yet). If the generator catches the exception and yields another value, that is the return value of g.throw(). If it doesn't catch the exception, the throw() appears to raise the same exception passed it (it falls through). If the generator raises another exception (this includes the StopIteration produced when it returns) that exception is raised by the throw() call. In summary, throw() behaves like next() or send(), except it raises an exception at the suspension point. If the generator is already in the closed state, throw() just raises the exception it was passed without executing any of the generator's code.
The effect of raising the exception is exactly as if the statement: raise type, value, traceback
was executed at the suspension point. The type argument must not be None, and the type and value must be compatible.
g.close() is defined by the following pseudo-code:
def close(self):
try:
self.throw(GeneratorExit)
except (GeneratorExit, StopIteration):
pass
else:
raise RuntimeError("generator ignored GeneratorExit")
# Other exceptions are not caught
https://www.python.org/dev/peps/pep-0342/
https://www.python.org/dev/peps/pep-0255/
Python2 生成器 简介的更多相关文章
- Python3.x:生成器简介
Python3.x:生成器简介 概念 任何使用yield的函数都称之为生成器:使用yield,可以让函数生成一个序列,该函数返回的对象类型是"generator",通过该对象连续调 ...
- 【翻译】ES6生成器简介
原文地址:http://davidwalsh.name/es6-generators ES6生成器全部文章: The Basics Of ES6 Generators Diving Deeper Wi ...
- Python基础之生成器
1.生成器简介 首先请确信,生成器就是一种迭代器.生成器拥有next方法并且行为与迭代器完全相同,这意味着生成器也可以用于Python的for循环中.另外,对于生成器的特殊语法支持使得编写一个生成器比 ...
- c#分布式ID生成器
c#分布式ID生成器 简介 这个是根据twitter的snowflake来写的.这里有中文的介绍. 如上图所示,一个64位ID,除了最左边的符号位不用(固定为0,以保证生成的ID都是正数),还剩余 ...
- python学习日记(迭代器、生成器)-乱七八糟
迭代器 迭代是Python最强大的功能之一,是访问集合元素的一种方式. 迭代器是一个可以记住遍历的位置的对象. 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束.迭代器只能往前不会后退 ...
- 【awesome-dotnet-core-learning】(3)-Bogus-假数据生成器
[awesome-dotnet-core-learning](3)-Bogus-假数据生成器 简介 Bogus一个简单而强大的假数据生成器,用于C#,F#和VB.NET.从著名的faker.js移植过 ...
- 【scikit-learn】06:make_blobs聚类数据生成器
版权声明:本文为博主原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/kevinelstri/article/ ...
- PythonI/O进阶学习笔记_9.python的生成器
content: 1. 什么是生成器 2. 生成器的实现 3. 生成器的应用 一.生成器简介 1.什么是生成器 在 Python 中,使用了 yield 的函数被称为生成器(genera ...
- 生成器和迭代器_python
一.生成器简介(generator) 在进行较大数据的存储,如果直接存储在列表之中,则会可能造成内存的不够与速度的减慢,因为列表创建完是立即创建并存在的,而在python中生成器(generator) ...
随机推荐
- centos7下python3和pycharm安装
1.python3安装 直接到官网下载或在以下地址下载让后解压安装 下载地址:https://www.python.org/ftp/python/ 安装参考博客:https://www.cnblogs ...
- JAVA_环境配置
1:系统环境 windows10 64位 jdk版本:jdk-8u131-windows-x64.exe,下载地址:http://www.oracle.com/technetwork/java/jav ...
- 两天了。照着SVN的界面画的一个界面。
可以选择显示哪些列. 界面上的东西,都简单,麻烦的是它的下层.下层全部用svn server的服务器自带的svn.exe来支持. 有些位置要启动svn.exe不止一次.所以参数的来回传递,来回组合 ...
- 《2018年云上挖矿态势分析报告》发布,非Web类应用安全风险需重点关注
近日,阿里云安全团队发布了<2018年云上挖矿分析报告>.该报告以阿里云2018年的攻防数据为基础,对恶意挖矿态势进行了分析,并为个人和企业提出了合理的安全防护建议. 报告指出,尽管加密货 ...
- 利用webuploader插件上传图片文件,完整前端示例demo,服务端使用SpringMVC接收
利用WebUploader插件上传图片文件完整前端示例demo,服务端使用SpringMVC接收 Webuploader简介 WebUploader是由Baidu WebFE(FEX)团队开发的一 ...
- 常用web字体的使用指南
而真正的挑战在于中文字体,由于中文字体组成的特殊性导致其体积过于庞大,除了操作系统内置的字体之外,我们很难在网站上应用其他的字体.在可选性很差的前提之下,如何正确的使用中文字体呢? 首先,以下的字体声 ...
- message d:\WEB_APP_QuChongFu\file\五月.xlsx (文件名、目录名或卷标语法不正确。)
原因是 文件名或文件夹名中不能出现以下字符:\ / : * ? " < > | 但是后台读取到的附件的文件路径就是这样的 网上大佬说了,这样处理 rep ...
- 如何在TypeScript中使用JS类库
使用流程 1.首先要清除类库是什么类型,不同的类库有不同的使用方式 2.寻找声明文件 JS类库一般有三类:全局类库.模块类库.UMD库.例如,jQuery是一种UMD库,既可以通过全局方式来引用,也可 ...
- MacBook下为要运行的.net core 项目指定sdk版本
安装完.net core 3.0,运行早期版本构建的项目遇到运行错误,查阅官方文档解决问题,特此记录!官方原文如下: SDK 使用最新安装的版本 SDK 命令包括 dotnet new 和 dotne ...
- 一段简单简介的JAVA内存分页代码
1.原因 工作中有的时候我们要处理的分页是无法全部用数据库去处理的,因为有些业务数据需要计算,所以我们需要把数据拿到程序中去分页 2.代码 //前端传入分页参数 Pageable pageable = ...