笔记-python-语法-yield

1.      yield

1.1.    yield基本使用

def fab(max):

n,a,b = 0, 0, 1

while n < max:

yield b

a, b = b, a+b

n = n + 1

f = fab(7)

print(f)

for i in f:

print(i)

1.2.    解释

在python 语法参考6.2.9中是这样描述的:

The yield expression is used when defining a generator function or an asynchronous generator function and thus can only be used in the body of a function definition. Using a yield expression in a function’s body causes that function to be a generator, and using it in an async def function’s body causes that coroutine function to be an asynchronous generator.

当一个生成器函数被调用时,它返回一个生成器(迭代器);

当它暂停时,会保存

all local state, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling.

1.3.    Generator-iterator methods

下面的章节描述了生成迭代器的方法,使用它们可以控制生成器函数的行为。

Note that calling any of the generator methods below when the generator is already executing raises a ValueErrorexception.

generator.__next__()

Starts the execution of a generator function or resumes it at the last executed yield expression. When a generator function is resumed with a __next__() method, the current yield expression always evaluates to None. The execution then continues to the next yield expression, where the generator is suspended again, and the value of the expression_list is returned to __next__()’s caller. If the generator exits without yielding another value, a StopIteration exception is raised.

This method is normally called implicitly, e.g. by a for loop, or by the built-in next() function.

generator.send(value)

Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value.

generator.throw(type[, value[, traceback]])

Raises an exception of type type at the point where the generator was paused, and returns the next value yielded by the generator function. If the generator exits without yielding another value, a StopIteration exception is raised. If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller.

generator.close()

Raises a GeneratorExit at the point where the generator function was paused. If the generator function then exits gracefully, is already closed, or raises GeneratorExit (by not catching the exception), close returns to its caller. If the generator yields a value, a RuntimeError is raised. If the generator raises any other exception, it is propagated to the caller. close() does nothing if the generator has already exited due to an exception or normal exit.

1.4.  Examples

Here is a simple example that demonstrates the behavior of generators and generator functions:

>>> 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.

1.5.    更多的案例

1.5.1.   example:1

def node._get_child_candidates(self, distance, min_dist, max_dist):

if self._leftchild and distance - max_dist < self._median:

yield self._leftchild

if self._rightchild and distance + max_dist >= self._median:

yield self._rightchild

1.5.2.   send案例

send有点不同

def func_yield():

x = yield 8

print(x)

x = yield x+6

print(x)

x = yield 23

print(x)

return 14

a = func_yield()

print('step 1:')

print(a.send(None))

print('step 2:')

print(a.send(11))

print('step 3:')

print(a.send(12))

print(a.send(13))

输出:

step 1:

8

step 2:

11

17

step 3:

12

23

13

Traceback (most recent call last):

File "E:\python\person_code\python_foundation\python_other.py", line 403, in <module>

print(a.send(13))

StopIteration: 14

send是先执行赋值后执行yield,

或者说x=yield 7等于

yield 7

x = val

最后一定是抛出一个异常来结束。

笔记-pytho-语法-yield的更多相关文章

  1. 笔记-jinja2语法

    笔记-jinja2语法 1.      基本语法 控制结构 {% %} 变量取值 {{ }} 注释 {# #} 2.      变量 最常用的是变量,由Flask渲染模板时传过来,比如上例中的”nam ...

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

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

  3. 《Java笔记——基础语法》

    Java笔记--基础语法       一.字符串的拼接: 例如: System.out.println(""+"");     二.换行语句: 例如: Syst ...

  4. Hive笔记--sql语法详解及JavaAPI

    Hive SQL 语法详解:http://blog.csdn.net/hguisu/article/details/7256833Hive SQL 学习笔记(常用):http://blog.sina. ...

  5. 读书笔记(06) - 语法基础 - JavaScript高级程序设计

    写在开头 本篇是小红书笔记的第六篇,也许你会奇怪第六篇笔记才写语法基础,笔者是不是穿越了. 答案当然是没有,笔者在此分享自己的阅读心得,不少人翻书都是从头开始,结果永远就只在前几章. 对此,笔者换了随 ...

  6. Javascript DOM 编程艺术(第二版)读书笔记——基本语法

    Javascript DOM 编程艺术(第二版),英Jeremy Keith.加Jeffrey Sambells著,杨涛.王建桥等译,人民邮电出版社. 学到这的时候,我发现一个问题:学习过程中,相当一 ...

  7. Python学习笔记——基础语法篇

    一.Python初识(IDE环境及基本语法,Spyder快捷方式) Python是一种解释型.面向对象.动态数据类型的高级程序设计语言,没有编译过程,可移植,可嵌入,可扩展. IDE 1.检查Pyth ...

  8. Python笔记_1语法总结

    前言导读 本章知识点是我在最初期听python视频教程的时候整理总结的笔记 对python语法的认识对以后代码的解读有着很大的帮助. 1 新建python命名规则 新建项目名 :数字编号 项目名称 新 ...

  9. [Python]Python入门笔记:语法基础

    Python笔记 一.基本语法 1.1 注释 文档注释: """contents""" 多行注释: ''' contents ''' 单行注 ...

随机推荐

  1. 内表转WORD

    组合HTML字符串的方法来导出WORD文件 DATA: BEGIN OF wa_html, zhtml(), END OF wa_html, gt_html LIKE TABLE OF wa_html ...

  2. (转)ArcEngine读取数据(数据访问)

    读取和访问数据是进行任何复杂的空间分析及空间可视化表达的前提,ArcGIS支持的数据格式比较丰富,下面就这些格式Shapefile.Coverage.Personal Geodatabase.Ente ...

  3. Html5 web本地存储

    Web Storage是HTML5引入的一个非常重要的功能,可以在客户端本地存储数据,类似HTML4的cookie,但可实现功能要比cookie强大的多,cookie大小被限制在4KB,Web Sto ...

  4. java集合框架——工具类

    一.概述 JAVA集合框架中有两个很重要的工具类,一个是Collections,另一个是Arrays.分别封装了对集合的操作方法和对数组的操作方法,这些操作方法使得程序员的开发更加高效. public ...

  5. RF脚本中的坑1: SyntaxError: invalid token

    话不多说,直接上调试脚本: 执行后${b}=8:没问题.然后${a}改成08继续: 执行后居然报错了: 经过多次尝试08或者09时,都会报SyntaxError错误:后来查阅语法,才恍然大悟:Pyth ...

  6. 问答 请问使用OK("raw:jpg")能返回多张图片吗

     请问使用OK("raw:jpg")能返回多张图片吗  发布于 28天前  作者 qq_3aeeb0ad  78 次浏览  复制  上一个帖子  下一个帖子  标签: 无 @At( ...

  7. Angular2入门--架构概览

    Angular 介绍 Angular 是一款来自谷歌的开源的web前端框架,诞生于2009年,是一款优秀的前端JS框架,已经被用于谷歌的多款产品. Angular 基于Typescript开发 ,更适 ...

  8. CKEditor4x word导入不保存格式的解决方案

    后台上传文档时,目前功能都通过word直接复制黏贴实现,之前和word控件朋友一起测试找个问题,原始代码CK4.X没有找个问题. 第一时间排查config.js的配置发现端倪,测试解决! 由于配合ck ...

  9. 使用QT开发GoogleMap瓦片显示和下载工具(1)——QT开发环境准备

    由于是第一次使用qt,光是QT的安装和调试就费了好大功夫,汗一个,下面记录下过程和遇到的问题的解决方法吧. 下载QT 直接Google搜索“QT”,进入官网http://qt-project.org/ ...

  10. Linux下C程序进程地址空间布局[转]

    我们在学习C程序开发时经常会遇到一些概念:代码段.数据段.BSS段(Block Started by Symbol) .堆(heap)和栈(stack).先看一张教材上的示意图(来源,<UNIX ...