首頁  >  文章  >  後端開發  >  Python 3.3 生成器中 Return 和 Yield 如何協同運作?

Python 3.3 生成器中 Return 和 Yield 如何協同運作?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-25 04:39:02244瀏覽

How Do Return and Yield Work Together in Python 3.3 Generators?

在Python 產生器中同時使用Return 和Yield

在Python 2 中,生成器內也使用了Yield 的return 語句將導致一個錯誤。然而,在 Python 3.3 中,卻發生了微妙的變化。

程式碼示範

考慮以下Python 3.3 程式碼:

<code class="python">def f():
  return 3
  yield 2
  
x = f()
print(x.__next__())</code>

在說明

當透過呼叫其 next 方法迭代產生器 x 時,會引發 StopIteration 異常,其值為 3。這表示生成器的迭代器耗盡,return 語句傳回的值可作為異常的 value 屬性。

Python 3.3 中的新機制
<code class="python">def f():
  yield 3
  raise StopIteration</code>

根據 PEP 380 ,此行為是 Python 3.3 中引入的新功能。它相當於編寫:

Yield from
<code class="python">def f():
    return 1
    yield 2

def g():
    x = yield from f()
    print(x)

# g is still a generator so we need to iterate to run it:
for _ in g():
    pass</code>

範例以下範例示範了此行為如何影響使用yield from語法委託的生成器: 在這種情況下,yield from 語句委託給生成器f。由於 f 傳回一個值,但不再有yield 語句,因此列印值 1。然而,f中的yield 2語句並沒有被執行。

以上是Python 3.3 生成器中 Return 和 Yield 如何協同運作?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn