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. 深入理解JavaScript系列(11):执行上下文(Execution Contexts)

    简介 从本章开始,我将陆续(翻译.转载.整理)http://dmitrysoshnikov.com/网站关于ECMAScript标标准理解的好文. 本章我们要讲解的是ECMAScript标准里的执行上 ...

  2. A bug about RecipientEditTextView

    - Steps to reproduce the problem. Pre-condition:the threshold of the RecipientEditTextView is set to ...

  3. Java集合篇四:Map的基本应用

    package com.test.collection; import java.util.HashMap; import java.util.Hashtable; import java.util. ...

  4. scss-&父选择器标识符

    在使用选择器嵌套的时候有一种情况需要特别注意,先看一段scss代码实例: .text a { color: blue; :hover { color: red } } 也许写此段代码目的是为了将其编译 ...

  5. Stage4--Python面向对象

    说在前面: Stage1-Stage4简单介绍一下Python语法,Stage5开始用python实现一些实际应用,语法的东西到处可以查看到,学习一门程序语言的最终目的是应用,而不是学习语法,语法本事 ...

  6. git push & git pull 推送/拉取分支

    git push与git pull是一对推送/拉取分支的git命令. git push 使用本地的对应分支来更新对应的远程分支. $ git push <远程主机名> <本地分支名& ...

  7. Android 笔记之 Android 系统架构

    Android笔记之Android系统架构 h2{ color: #4abcde; } a{ color: blue; text-decoration: none; } a:hover{ color: ...

  8. Java环境路径配置--转载

    windows环境中JDK环境变量配置   一.环境准备 Windows10 jdk-9.0.1 二.下载并安装JDK 到Java的官网下载JDK安装包,地址:http://www.oracle.co ...

  9. CSS3控制单行文本的溢出

    text-overflow用来设置是否使用一个省略标记(...)标示对象内文本的溢出.语法: 但是text-overflow只是用来说明文字溢出时用什么方式显示,要实现溢出时产生省略号的效果,还须定义 ...

  10. 解决未安装unit测试和jest的Vue项目运行karma start时的错误

    一.起因 在#单元测试#以karma+mocha+chai 为测试框架的Vue webpack项目(一)文中,说明了是对已有的Vue项目进行测试框架的搭建,并进行测试.但是此项目在利用 vue-cli ...