当前位置: 移动技术网 > IT编程>脚本编程>Python > python之yield表达式

python之yield表达式

2018年10月07日  | 移动技术网IT编程  | 我要评论

香河老人,夏恒,情有独钟歌词

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.

模拟个iteratorrange函数

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


if __name__ == '__main__':
    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)

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网