python之yield表达式
yield表达式用于generator function
调用generator function时,返回一个iterator(函数内语句不被会执行),调用iterator函数时,执行到yield表达式,
当前函数暂停执行,返回表达式的值到调用者,继续调用iterator函数,从暂停处恢复执行。、
遇到yield表达式,与遇到其他表达式差不多,yield表达式也有值,一般为None。
与其他表达式的不同之处在于yield表达式会在yield处返回表达式的值
官方文档描述如下:
When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of the generator function. The execution starts when one of the generator’s methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to the generator’s caller. By suspended, we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by calling one of the generator’s methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If __next__() is used (typically via either a for or the next() builtin) then the result is None. Otherwise, if send() is used, then the result will be the value passed in to that method.
Yield expressions are allowed anywhere in a try construct. If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator’s close() method will be called, allowing any pending finally clauses to execute.
When the underlying iterator is complete, the value attribute of the raised StopIteration instance becomes the value of the yield expression.
官方例子:
>>> def echo(value=None):
... print("Execution starts when 'next()' is called for the first time.")
... try:
... while True:
... try:
... value = (yield value)
... except Exception as e:
... value = e
... finally:
... print("Don't forget to clean up when 'close()' is called.")
...
>>> generator = echo(1)
>>> print(next(generator))
Execution starts when 'next()' is called for the first time.
1
>>> print(next(generator))
None
>>> print(generator.send(2))
2
>>> generator.throw(TypeError, "spam")
TypeError('spam',)
>>> generator.close()
Don't forget to clean up when 'close()' is called.
模拟个iterator版range函数
def my_range(start, stop=None, step=1):
if not stop:
stop = start
start = 0
while start < stop:
yield start
start += step if __name__ == '__main__':
for i in my_range(10):
print(i)
for i in my_range(0, 10):
print(i)
for i in my_range(0, 10, 2):
print(i)
python之yield表达式的更多相关文章
- python 之 yield表达式
如果在某个函数中包含了yield, 这意味着这个函数已经是一个Generator, 它的执行 会和其他普通的函数有很多不同. 比如: def h(): print 'To be bra ...
- Python语法 - yield表达式(类似 m = yield i )
yield是个表达式而不仅仅是个语句,所以可以使用x = yield r 这样的语法, yield表达式可以接收send()发出的参数,yield表达式是跟send方法一起配合使用 send方 ...
- Python基础(9)_生成器(yield表达式形式)、面向过程编程
一.yield表达式形式 1 #装饰器,初始化含yield表达式的生成器 def init(func): def wrapper(*args,**kwargs): g=func(*args,**kwa ...
- Python 3 中生成器函数yield表达式的使用
生成器函数或生成器方法中包含了一个yield表达式.调用生成器函数时,会返回一个迭代子,值从迭代子中每次提取一个(通过调用其__next__()方法).每次调用__next__()时,生成器函数的yi ...
- python函数式编程之yield表达式形式
先来看一个例子 def foo(): print("starting...") while True: res = yield print("res:",res ...
- yield表达式 python语法
可以先看下这篇文章:http://www.cnblogs.com/jiangtu/articles/6662043.html 原篇是转载的:http://www.python-tab.com/html ...
- python中yield用法
在介绍yield前有必要先说明下Python中的迭代器(iterator)和生成器(constructor). 一.迭代器(iterator) 在Python中,for循环可以用于Python中的任何 ...
- Python中yield深入理解
众所周知,python中的yield有这样的用法: def test(alist): for i in alist: yield i 这样,这个test函数就变成了一个生成器,当每次调用的时候,就会自 ...
- yield表达式形式
首先了解 1.iterator iterator叫做迭代器,用来遍历可以序列化的数据,比如一个list,set 等,当然如果对象想要能够使用迭代器来遍历,只要在该对象的类中添加__iter__()方法 ...
随机推荐
- 深入理解JavaScript系列(37):设计模式之享元模式
介绍 享元模式(Flyweight),运行共享技术有效地支持大量细粒度的对象,避免大量拥有相同内容的小类的开销(如耗费内存),使大家共享一个类(元类). 享元模式可以避免大量非常相似类的开销,在程序设 ...
- 10、选择框:ion-select
!重点 multiple="true" 控制 选择框是 多选还是单选.true为 多选类似 checkbox. /* ---html----*/ <ion-content p ...
- jquery监控input输入框的变化
(function($) { $.fn.watch = function(callback) { return this.each(function() { //缓存以前的值 $.data(this, ...
- CentOS初使用命令总结
最近买了一台aliyun(ECS服务器)用来学习使用,初次使用难免要走弯路.遇到一些问题好长时间解决不了,结果经人指点豁然开朗.于是乎,总结了一些新生上路经验. 首先要解决的问题是:通过PuTTY.S ...
- 再写一篇ubuntu服务器的环境配置文
三年前写过一篇,但是环境和三年前比已经发生了比较大的变化,于是重新写一篇,自己以后再次配置也比较方便.我个人而言并没有觉得centos比ubuntu好用多少,所以继续选用ubuntu. 一.硬盘分区 ...
- HDU 5007 字符串匹配
http://acm.hust.edu.cn/vjudge/contest/122814#problem/A 匹配到字符串就输出,水题,主要是substr的运用 #include <iostre ...
- git丢弃修改
丢弃本地所有更改: git fetch origin git reset --hard origin/[对应的分支] 更改上次提交的注释: git commit --amend 会进到(vim编 ...
- shell 复制/备份文件 脚本
#!/bin/sh # author hapday # -- echo "以时间日期为名称基准备份 war 包." date +%Y-%m-%d-%H-%M-%S cp artup ...
- 提交自己的包到 npm 中
npm npm全称Node Package Manager,是node.js的模块依赖管理工具.使用github管理NPM包的代码,并定期提交至NPM服务器:npm官网 提交自己开发的NPM包 创建p ...
- CSS3媒体查询总结
1.什么是媒体查询 媒体查询可以让我们根据设备显示器的特性(如视口宽度.屏幕比例.设备方向:横向或纵向)为其设定CSS样式,媒体查询由媒体类型和一个或多个检测媒体特性的条件表达式组成.媒体查询中可用于 ...