如何传递yield

作者: 曹建峰 | 来源:发表于2017-04-06 10:28 被阅读0次

有时候我们需要把一个函数的yield结果传递给另一个函数,怎么实现呢?

先说一下我研究的结果:

需要在中间函数中遍历上一个函数的结果,然后逐条yield调用。
例如下面的fun3() 就是可以传递的yield。

源码例子1:test_yield2.py for python2.x


def fun1():
    for i in range(1, 10):
        yield i


def fun2():
    yield fun1()


def fun3():
    f = fun1()
    has_next = True
    while has_next:
        try:
            val = f.next()
            print "fun3 got %d" % val
            yield val
        except StopIteration, e:
            has_next = False
            print " fun3    Finish!   "

f_tested = fun3()
has_next = True
while has_next:
    try:
        val = f_tested.next()
        print val
    except StopIteration, e:
        has_next = False
        print "     Finish!   "

源码例子2:test_yield3.py for python3.x

def fun1():
    for i in range(1, 10):
        yield i


def fun2():
    yield fun1()


def fun3():
    f = fun1()
    for item in f:
        print("fun3 got %d" % item)
        yield item


f_tested = fun3()
has_next = True

for item in f_tested:
    print(item)

print ("     Finish!   ")

f_tested = fun1()时的输出

$ python testYield.py 
1
2
3
4
5
6
7
8
9
     Finish!   

f_tested = fun2()时的输出

$ python test_yield.py 
<generator object fun1 at 0x10efeab40>
     Finish!   

f_tested = fun3()时的输出

$ python test_yield.py 
fun3 got 1
1
fun3 got 2
2
fun3 got 3
3
fun3 got 4
4
fun3 got 5
5
fun3 got 6
6
fun3 got 7
7
fun3 got 8
8
fun3 got 9
9
 fun3    Finish!   
     Finish!   

相关文章

  • 如何传递yield

    有时候我们需要把一个函数的yield结果传递给另一个函数,怎么实现呢? 先说一下我研究的结果: 需要在中间函数中遍...

  • Python yield

    Python yield的用法详解 如何快速的对yield有一个初步的了解,那么首先我们可以先将yield看做是r...

  • 协程

    从yield说起 当生成器执行到yield的时候,通过send方法向生成器传递一个值,生成器在收到传进来的值之后,...

  • Python生成器进阶

    一、yield 简介 二、yield from 功能总结: 三、yield from 的用法:

  • python yield和yield from用法总结

    python yield和yield from用法总结 yield 作用: 注: generator的next()...

  • JAVA多线程08-基础篇-线程让步yield()

    本节摘要:yield()功能介绍,yield()用法示例 一、功能介绍 让当前线程(调用yield()方法的线程)...

  • Python yield

    参考:Python yield 使用浅析 - IBM 递归中使用yield 有时候yield就可以解决递归的问题,...

  • pytest-fixture中的yield及autouse

    记录一下fixture中关于yield以及autouse参数的两个小细节。 yield yield在fixture...

  • CFA level I 数量方法错点

    bank discount yield 360天 effective annual yield 365天 Any ...

  • Python yield关键字

    Python中yield关键字解释 这篇文章关于python的yield关键字。并且文章中会解释什么是yield,...

网友评论

    本文标题:如何传递yield

    本文链接:https://www.haomeiwen.com/subject/gobfattx.html