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表达式的更多相关文章

  1. python 之 yield表达式

    如果在某个函数中包含了yield, 这意味着这个函数已经是一个Generator, 它的执行 会和其他普通的函数有很多不同. 比如: def   h(): print    'To   be  bra ...

  2. Python语法 - yield表达式(类似 m = yield i )

      yield是个表达式而不仅仅是个语句,所以可以使用x = yield r 这样的语法, yield表达式可以接收send()发出的参数,yield表达式是跟send方法一起配合使用   send方 ...

  3. Python基础(9)_生成器(yield表达式形式)、面向过程编程

    一.yield表达式形式 1 #装饰器,初始化含yield表达式的生成器 def init(func): def wrapper(*args,**kwargs): g=func(*args,**kwa ...

  4. Python 3 中生成器函数yield表达式的使用

    生成器函数或生成器方法中包含了一个yield表达式.调用生成器函数时,会返回一个迭代子,值从迭代子中每次提取一个(通过调用其__next__()方法).每次调用__next__()时,生成器函数的yi ...

  5. python函数式编程之yield表达式形式

    先来看一个例子 def foo(): print("starting...") while True: res = yield print("res:",res ...

  6. yield表达式 python语法

    可以先看下这篇文章:http://www.cnblogs.com/jiangtu/articles/6662043.html 原篇是转载的:http://www.python-tab.com/html ...

  7. python中yield用法

    在介绍yield前有必要先说明下Python中的迭代器(iterator)和生成器(constructor). 一.迭代器(iterator) 在Python中,for循环可以用于Python中的任何 ...

  8. Python中yield深入理解

    众所周知,python中的yield有这样的用法: def test(alist): for i in alist: yield i 这样,这个test函数就变成了一个生成器,当每次调用的时候,就会自 ...

  9. yield表达式形式

    首先了解 1.iterator iterator叫做迭代器,用来遍历可以序列化的数据,比如一个list,set 等,当然如果对象想要能够使用迭代器来遍历,只要在该对象的类中添加__iter__()方法 ...

随机推荐

  1. Windows无法启动MySQL服务,错误1067

    问题:mysql服务启动异常 找出原因 检查D:\mysql-5.6.20-winx64\data目录下client-02.err文件的错误信息(以err为后缀名的文件是mysql的日志文件) 修改配 ...

  2. Wpf ListView展示风格

    ListView数据绑定控件,通常是竖列展示,也可以通过改变ListView的布局来改变它的展示方式 如图展示: 主要需用修改的样式如下: <!--GridView Header样式 去除Gri ...

  3. HTML表格相关元素

    <table> 标签定义 HTML 表格.简单的 HTML 表格由 table 元素以及一个或多个 tr.th 或 td 元素组成.tr 元素定义表格行,th 元素定义表头,td 元素定义 ...

  4. 转:HTML中让图片滚动的<marquee>标签的使用方法

    实例: <marquee id="affiche" align="left" behavior="scroll" bgcolor=&q ...

  5. 转:如何利用已有的切片文件生成TPK

    Tpk是ArcGIS 10.1即将推出的一种新的数据文件类型,主要是用于将切片文件打包形成离线地图包.Tpk可以在ArcGIS Runtime中作为切片底图被加载.在ArcGIS 10.1中Tpk的生 ...

  6. 避免Autoclose和Autoshrink选项

    避免Autoclose和Autoshrink选项发布日期:2001年12月18日 问题:我在Microsoft SQL Server 2000资源工具包中读到了一个用于就应当避免使用的选项对所有数据库 ...

  7. SQL Server ->> CLR存储过程枚举目录文件并返回结果集

    因工作需要写了个CLR存储过程枚举目录文件并返回结果集 using System; using System.IO; using System.Collections.Generic; using S ...

  8. oracle模糊搜索避免使用like,替换为instr()

    oracle中instr()函数用法 instr(name,'张三')>0  相当于  name like '%张三%' instr(name,'张三')=1  相当于  name like ' ...

  9. Oracle 11.1.0.6 导入导出bug

    实验环境: 11.1.0.6.0   对ANONYMOUSUSER_ALL表中分区进行备份 SQL> select TABLE_NAME,PARTITION_NAME,HIGH_VALUE,PA ...

  10. Orchard Core 文档翻译 (三) Orchard Core Modules

    原文连接:https://www.cnblogs.com/Qbit/p/9746442.html 转载请注明出处 介绍 Orchard Core Modules库提供了一种机制,可以拥有一个独立的模块 ...