zoukankan      html  css  js  c++  java
  • python生成器

    什么是 python 式的生成器?从句法上讲,生成器是一个带 yield 语句的函数。一个函数或者子
    程序只返回一次,但一个生成器能暂停执行并返回一个中间的结果----那就是 yield 语句的功能,返
    回一个值给调用者并暂停执行。当生成器的 next()方法被调用的时候,它会准确地从离开地方继续
    (当它返回[一个值以及]控制给调用者时)

    简单实例

    1. def gen():
    2. yield 1
    3. yield 2
    4. yield 3
    5. f = gen()
    6. print f.next()
    7. print f.next()
    8. print f.next()

    输出结果

    1. 1
    2. 2
    3. 3

    从结果我们可以看出每次调用函数对象的next方法时,总是从上次离开的地方继续执行的.

    加强的生成器

    在 python2.5 中,一些加强特性加入到生成器中,所以除了 next()来获得下个生成的值,用户
    可以将值回送给生成器[send()],在生成器中抛出异常,以及要求生成器退出[close()]

    1. def gen(x):
    2. count = x
    3. while True:
    4. val = (yield count)
    5. if val is not None:
    6. count = val
    7. else:
    8. count += 1
    9. f = gen(5)
    10. print f.next()
    11. print f.next()
    12. print f.next()
    13. print '===================='
    14. print f.send(9)#发送数字9给生成器
    15. print f.next()
    16. print f.next()

    输出

    1. 5
    2. 6
    3. 7
    4. ====================
    5. 9
    6. 10
    7. 11




  • 相关阅读:
    单步调试及回滚测试
    程序员的自我修养阅读笔记03
    第八周总结
    NABCD项目分析
    程序员的自我修养阅读笔记02
    第七周总结
    程序员的自我修养阅读笔记01
    第六周总结
    结对地铁开发
    第五周总结
  • 原文地址:https://www.cnblogs.com/csu_xajy/p/4342729.html
Copyright © 2011-2022 走看看