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. 学习安卓开发过程中遇到关于R.Java文件的问题

    在学习安卓开发过程时,遇到R.java生成问题,总结几个方法解决. 1.首先必须做的就是检查代码的正确性,存在错误的代码,不编译生成R.java 2.右键点项目,选择 Android Tools -& ...

  2. mysql应用学习-解决数据乱码

    原因 mysql数据库character_set_database和character_set_server默认编码是latin1,所以导致乱码: 修改步骤 step1. 修改my.ini配置 在[m ...

  3. 如何恢复sqlserver误删除的数据(摘)

    一.借助第三方工具 1.sqlserver2005: Log Explorer http://www.cnblogs.com/whitney/archive/2008/08/22/1273879.ht ...

  4. mvc中在Action里调用另一个Action

    今天做东西时发现一个新东西.即在一个Action调用另一Action.前提是同一个控制器.(没在一个控制里的没试过) 调用方法: public   ActionResult Test1(){ //to ...

  5. (三)css之浮动&定位

    众所周知,一个页面可能包含多个div,如何对这些div进行排列,以便具有较好的显示效果呢? css提供了浮动和定位两个属性进行div的排列,下面主要针对浮动和定位进行详细地阐述. (一)何为浮动? 浮 ...

  6. laravel vue.js的使用

    安装cors    地址:https://github.com/barryvdh/laravel-cors 在Kernel文件中加上 protected $middleware = [ \Barryv ...

  7. 如何禁用 Azure 虚拟机的日期时间同步

    问题描述 由于 Azure 虚拟机的特殊性,物理主机会实时同步虚拟机的时间和日期.当有特殊需求时,客户想要停止日期时间的同步,但是一些常见的关闭 NTP 服务等操作都会失败. 解决方案 Importa ...

  8. June 14th 2017 Week 24th Wednesday

    Love looks not with the eyes, but with the mind. 爱,不在眼里,而在心中. Staring in her eyes and you will find ...

  9. Python3基本数据类型(一、数字类型)

    第一次写博客,感觉心情比较紧张,有一种要上台演讲的紧张感(虽然可能大概也许不会有人看).在此立个flag,以后每个学习阶段都要写一篇博客,来记录自己学习成长的这段日子.Fighting! 废话不多说, ...

  10. 团队第四次SCrum

    scrum 第四次冲刺 一.项目目的        为生活在长大的学生提供方快捷的生活服务,通过帖子发现自己志同道合的朋友,记录自己在长大点滴.本项目的意义在于锻炼团队的scrum能力,加强团队合作能 ...