首頁  >  文章  >  後端開發  >  python中yield表達式的簡單介紹(附範例)

python中yield表達式的簡單介紹(附範例)

不言
不言轉載
2018-10-08 16:25:312735瀏覽

這篇文章帶給大家的內容是關於python中yield表達式的簡單介紹(附範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

yield表達式用於generator function

呼叫generator function時,傳回一個iterator(函數內語句不會被執行),呼叫iterator函數時,執行到yield表達式,

目前函數暫停執行,返回表達式的值到呼叫者,繼續呼叫iterator函數,從暫停處恢復執行。 、

遇到yield表達式,與遇到其他表達式差不多,yield表達式也有值,一般為None。

與其他表達式的不同之處在於yield表達式會在yield處傳回表達式的值

官方文件描述如下:

When a generator function is called , it returns an iterator known as a generator. That generator then controls the execution of the generator function. The execution starts when one of the generator’s methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to the generator’s caller. By suspended, we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by calling one of the generator’s methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If __next__() is used (typically via either a for or the next() builtin) then the result is None. Otherwise, if send() is used, then the result will be the value passed in to that method.

Yield expressions are allowed anywhere in a try construct. If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator’s close() method will be called, allowing any pending finally clauses to execute.

 When the underlying iterator is complete, the value attribute of the raised StopIteration instance becomes the value of the yield expression.

官方範例:

>>> def echo(value=None):
...     print("Execution starts when 'next()' is called for the first time.")
...     try:
...         while True:
...             try:
...                 value = (yield value)
...             except Exception as e:
...                 value = e
...     finally:
...         print("Don't forget to clean up when 'close()' is called.")
...>>> generator = echo(1)>>> print(next(generator))
Execution starts when 'next()' is called for the first time.1
>>> print(next(generator))
None>>> print(generator.send(2))2
>>> generator.throw(TypeError, "spam")
TypeError('spam',)>>> generator.close()
Don't forget to clean up when 'close()' is called.

類比個iterator range函數

def my_range(start, stop=None, step=1):
    if not stop:
        stop = start
        start = 0
    while start < stop:
        yield start
        start += step


if __name__ == &#39;__main__&#39;:
    for i in my_range(10):
        print(i)
    for i in my_range(0, 10):
        print(i)
    for i in my_range(0, 10, 2):
        print(i)

以上是python中yield表達式的簡單介紹(附範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除