如果在一个函数中使用了yield,那么这个函数实际上生成的是一个生成器函数 ,返回的是一个generator object。生成器是实现迭代的一种方式

特点:

  • 其实返回的就是可以的迭代对象
  • 和迭代的方法一样,可以使用next(),for循环的方法取值:
  • 当一个yeild语句被执行,这个迭代器(函数)的状态像是被冻结(frozen)了一样并且返回next()调用的结果
  • 协程
The "yield" statement
*********************

   yield_stmt ::= yield_expression

The "yield" statement is only used when defining a generator function,
and is only used in the body of the generator function. Using a
"yield" statement in a function definition is sufficient to cause that
definition to create a generator function instead of a normal
function.
"yield"语句仅用于当定义一个生成器函数并且作为这个生成器函数的主体
在一个函数内容使用yiled足以创建一个生成器函数,来替代普通的函数.

When a generator function is called, it returns an iterator known as a
generator iterator, or more commonly, a generator.  The body of the
generator function is executed by calling the generator's "next()"
method repeatedly until it raises an exception.
当一个生成器函数被调用,它返回一个迭代器称作生成器函数,或者一般的生成器,
这个生成器函数是通过next()方法反复的执行直到出现了异常

When a "yield" statement is executed, the state of the generator is
frozen and the value of "expression_list" is returned to "next()"'s
caller.  By "frozen" we mean that all local state is retained,
including the current bindings of local variables, the instruction
pointer, and the internal evaluation stack: enough information is
saved so that the next time "next()" is invoked, the function can
proceed exactly as if the "yield" statement were just another external
call.
当一个yeild语句被执行,这个迭代器的状态像是被冻结(frozen)并且返回next()调用的结果,
通过"frozen"意味着所有的局部(local)状态被保存,包括当前绑定的局部变量,指令指针.

As of Python version 2.5, the "yield" statement is now allowed in the
"try" clause of a "try" ...  "finally" 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.

For full details of "yield" semantics, refer to the Yield expressions
section.

Note: In Python 2.2, the "yield" statement was only allowed when the
  "generators" feature has been enabled.  This "__future__" import
  statement was used to enable the feature:

     from __future__ import generators

See also: **PEP 0255** - Simple Generators

     The proposal for adding generators and the "yield" statement to
     Python.

  **PEP 0342** - Coroutines via Enhanced Generators
     The proposal that, among other generator enhancements, proposed
     allowing "yield" to appear inside a "try" ... "finally" block.

help(yield)

1、如果函数遇到了return,这个函数就执行完了

def func1():
    return 'one'
    return 'two'
print func1()
one

2、如果将retrun换成yield

  • 返回的是一个generator(生成器)对象,可以通过next()方法取值直到抛出异常
  • 可以通过for循环迭代
def func1():
    yield 'one'
    yield 'two'
    yield 'three'
reslut = func1()
print reslut
StopIteration
print reslut.next()
one
print reslut.next()
two
print reslut.next()
three
print reslut.next()  #异常
StopIteration

for循环

for item in reslut:
    print item
one
two
three

2、实现类似xrange的功能

def mxrange(arg):
    temp = -1
    while True:
        temp = temp + 1
        if temp >= arg:
            return
        else:
            yield temp
for item in mxrange(10):
    print item,

总结:

  • yield用来做生成器函数,可以通过next()、for循环方法取值,只是遇到了yield时函数就像冻结一样,保存当前的变量,返回的是next()的结果
  • 和生成器、迭代器一样不用在内存中创建大量的数据,而是需要调用的时候通过迭代返回数据  

Python基础 (yield生成器)的更多相关文章

  1. 十三. Python基础(13)--生成器进阶

    十三. Python基础(13)--生成器进阶 1 ● send()方法 generator.send(value) Resumes the execution, and "sends&qu ...

  2. 十二. Python基础(12)--生成器

    十二. Python基础(12)--生成器 1 ● 可迭代对象(iterable) An object capable of returning its members one at a time. ...

  3. (转)python基础学习-----生成器和迭代器

    在Python中,很多对象都是可以通过for语句来直接遍历的,例如list.string.dict等等,这些对象都可以被称为可迭代对象.至于说哪些对象是可以被迭代访问的,就要了解一下迭代器相关的知识了 ...

  4. Python基础之生成器

    1.生成器简介 首先请确信,生成器就是一种迭代器.生成器拥有next方法并且行为与迭代器完全相同,这意味着生成器也可以用于Python的for循环中.另外,对于生成器的特殊语法支持使得编写一个生成器比 ...

  5. python 基础——generate生成器

    通过列表表达式可以直接生成列表,不过列表一旦生成就需要为所有元素分配内存,有时候会很消耗资源. 所以,如果列表元素可以按照某种算法推算出来,这样就不必创建完整的list,从而节省大量的内存空间. 在P ...

  6. python基础(八)生成器,迭代器,装饰器,递归

    生成器 在函数中使用yield关键字就会将一个普通的函数变成一个生成器(generator),普通的函数只能使用return来退出函数,而不执行return之后的代码.而生成器可以使用调用一个next ...

  7. Python基础(生成器)

    二.生成器(可以看做是一种数据类型) 描述: 通过列表生成式,我们可以直接创建一个列表.但是,受到内存限制,列表容量肯定是有限的.而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我 ...

  8. Day12 Python基础之生成器、迭代器(高级函数)(十)

    https://www.cnblogs.com/yuanchenqi/articles/5769491.html 1. 列表生成式 我现在有个需求,看列表[0, 1, 2, 3, 4, 5, 6, 7 ...

  9. python基础之生成器迭代器

    1 生成器: 为什么要有生成器? 就拿列表来说吧,假如我们要创建一个list,这个list要求格式为:[1,4,9,16,25,36……]这么一直持续下去,直到有了一万个元素的时候为止.如果我们要创建 ...

随机推荐

  1. 【新产品发布】《EVC8021 RS-232<>RS-485/422 隔离接口转换器》

    [数据手册下载] 1.百度云盘:(把下面蓝色连接复制到浏览器下打开) http://pan.baidu.com/s/1eQlJ0zC 2.淘宝公司的淘云盘:(点击下面连接后,需要用淘宝账户登录) ht ...

  2. OC中的属性、方法及内存管理

    普通方法:关注(代表)对象可以”干什么”,过程中需要实例变量.-(void)show;输出 … 访问属性    属性:属性专门处理实例变量.(程序执行过程当中)    初始化方法:一创建对象(第一时间 ...

  3. Mesa10.2在Win7上的编译

    Mesa10仍然支持Windwos/linux,但是编译方式已经不提供makefile或者workspace Building on windows requires several open-sou ...

  4. BNF 巴科斯范式

    BNF 巴科斯范式(BNF: Backus-Naur Form 的缩写)是由 John Backus 和 Peter Naur 首先引入的用来描述计算机语言语法的符号集.现在,几乎每一位新编程语言书籍 ...

  5. UDP 构建p2p打洞过程的实现原理(持续更新)

    UDP 构建p2p打洞过程的实现原理(持续更新) 发表于7个月前(2015-01-19 10:55)   阅读(433) | 评论(0) 8人收藏此文章, 我要收藏 赞0 8月22日珠海 OSC 源创 ...

  6. Web 软件测试 Checklist 应用系列,第 1 部分: 数据输入

    Web 软件测试 Checklist 应用系列,第 1 部分: 数据输入 本文为系列文章"Web 软件测试 Checklist 应用系列"中的第一篇.该系列文章旨在阐述 Check ...

  7. ecshop中$user对象

    ecshop中$user对象 2011-10-01 18:41:23|  分类: ECSHOP |  标签:ecshop  $user  对象  |举报|字号 订阅 http://blog.163.c ...

  8. SSH 基础

    什么是SSH? 传统的网络服务程序,如:ftp.pop和telnet在本质上都是不安全的,因为它们在网络上用明文传送口令和数据,别有用心的人非常容易就可以截获这些口令和数据.而且,这些服务程序的安全验 ...

  9. rsync安装及配置

    一.Server端 CentOS 6下安装yum -y install xinetd1.配置:vi /etc/xinetd.d/rsyncservice rsync{    disable = yes ...

  10. asp.net webform杂记

    context.Response.ContentType = "text/plain";            string encodeFileName = HttpUtilit ...