Joh*_*lén 8 python yield generator
我是一名C#程序员,试图理解一些Python代码.有问题的代码是生成器函数,如下所示:
def func():
oldValue = curValue
yield
curValue = oldValue
Run Code Online (Sandbox Code Playgroud)
如果我理解正确,这将生成一个包含一个成员的可迭代序列.但是,yield声明后没有表达.什么是这种无表达式的陈述应该产生什么?有没有使用这种编码方式的Python习语?
Mar*_*ers 11
它会产生None; 就像一个空return表达式:
>>> def func():
... yield
...
>>> f = func()
>>> next(f) is None
True
Run Code Online (Sandbox Code Playgroud)
你用它来暂停代码.之前,一切都yield在运行时,你第一个电话next()在发电机,之后的一切yield,当你打电话时只运行next()一次就可以了:
>>> def func():
... print("Run this first for a while")
... yield
... print("Run this last, but only when we want it to")
...
>>> f = func()
>>> next(f, None)
Run this first for a while
>>> next(f, None)
Run this last, but only when we want it to
Run Code Online (Sandbox Code Playgroud)
我使用了两参数形式next()来忽略StopIteration抛出的异常.以上内容并不关心yield编辑内容,只是在该点暂停了该功能.
对于一个实际的例子,@contextlib.contextmanager装饰者完全希望你以yield这种方式使用; 您可以选择 yield在目标中使用的with ... as对象.关键是yield当输入上下文时运行之前的所有内容,退出上下文后运行的所有内容.
| 归档时间: |
|
| 查看次数: |
432 次 |
| 最近记录: |