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__()方法 ...
随机推荐
- ThreadPoolExecutor(下篇)
上篇写到了ThreadPoolExecutor构造方法前4个参数int corePoolSize.int maximumPoolSize,.long keepAliveTime.TimeUnit un ...
- mysql基本面试题
1.MySQL的复制原理以及流程 基本原理流程,3个线程以及之间的关联: 1. 主:binlog线程——记录下所有改变了数据库数据的语句,放进master上的binlog中: 2. 从:io线程——在 ...
- 卸载Gac里被windows installer所reference的assembly的方法
HKEY_LOCAL_MACHINE\Software\Classes\Installer\Assemlies\Global下找到要删除的assembly的那一项, 删除. 然后再gacutil /u ...
- Ckrule业务规则管理系统简介
1. 简述 Ckrule业务规则管理系统(BRMS)是一个集成的应用程序存储.管理.执行和测试的平台,允许组织定义.部署.监控和维护运营系统使用的各种复杂决策逻辑.Ckrule BRMS 独立于核 ...
- 【IOS】IOS综合
取精华.去糟粕!适合iOS开发者的15大网站推荐 E:/IOS视频: IOS基础/01 苹果开发零基础教程 3780m --> 63h /02 IOS开发快速入门教程 /03 IOS开发进阶教 ...
- C语言指针的陷阱
C语言指针的陷阱 分类: C/Cpp 转自:http://blog.csdn.net/porscheyin/article/details/3461670 “C语言诡异离奇,陷阱重重,却获得了巨大 ...
- asyncio标准库7 Producer/consumer
使用asyncio.Queue import asyncio import random async def produce(queue, n): for x in range(1, n + 1): ...
- asyncio标准库3 HTTP client example
import aiohttp import asyncio import async_timeout async def fetch(session, url): async with async_t ...
- Nginx+Tomcat在Windows下做负载均衡
一. 为什么需要对Tomcat服务器做负载均衡 Tomcat服务器作为一个Web服务器,其并发数在300-500之间,如果有超过500的并发数便会出现Tomcat不能响应新的请求的情况,严重影响网站的 ...
- Nginx-php-mysql
1.依赖包 yum -y install pcre* openssl*2.phprpm -Uvh https://mirror.webtatic.com/yum/el6/latest.rpmyum i ...