python程序员

如何传递yield

2017-04-06  本文已影响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!   
上一篇下一篇

猜你喜欢

热点阅读