簡體   English   中英

在Python中從協程調用協程

[英]Calling coroutine from coroutine in python

我今天遇到了這個問題,但我不確定為什么會這樣:

def outside():
    print 'before'
    inside()
    print 'after'
    yield 'World'

def inside():
    print 'inside'
    yield 'Hello'

for n in outside():
    print n

(天真)對產量的期望:

before
inside
Hello
after
World

實際輸出:

before
after
World

無法從協程內部調用協程嗎? 我讀過的有關協程和產量的文章沒有詳細說明這個問題,我在這里很失落。 請問有人可以闡明這種行為嗎? 提前致謝!

這是完全可能的。 當您調用inside()它將創建一個協程。 為了產生結果,您需要初始化協程並從中產生如下:

def outside():
     print 'before'
     for i in inside():
         yield i
     print 'after'
     yield 'World'

結果將是預期的:

before
inside
Hello
after
World

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM