有時候我們需要把一個函數(shù)的yield結(jié)果傳遞給另一個函數(shù)冀自,怎么實現(xiàn)呢?
先說一下我研究的結(jié)果:
需要在中間函數(shù)中遍歷上一個函數(shù)的結(jié)果,然后逐條yield調(diào)用猿诸。
例如下面的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!