How can I run the initialization code for a generator function immediately, rather than at the first call?(如何立即运行生成器函数的初始化代码,而不是在第一次调用时?)
问题描述
我有一个类似这样的生成器函数:
I have a generator function that goes something like this:
def mygenerator():
next_value = compute_first_value() # Costly operation
while next_value != terminating_value:
yield next_value
next_value = compute_next_value()
我希望在调用函数后立即运行初始化步骤(在 while 循环之前),而不是仅在第一次使用生成器时运行.有什么好的方法可以做到这一点?
I would like the initialization step (before the while loop) to run as soon as the function is called, rather than only when the generator is first used. What is a good way to do this?
我想这样做是因为生成器将在单独的线程(或进程,或任何多处理使用)中运行,并且我不会在短时间内使用 return,而且初始化有点昂贵,所以我希望它在我准备使用这些值时进行初始化.
I want to do this because the generator will be running in a separate thread (or process, or whatever multiprocessing uses) and I won't be using the return for a short while, and the initialization is somewhat costly, so I would like it to do the initialization while I'm getting ready to use the values.
推荐答案
class mygenerator(object):
def __init__(self):
next_value = compute_first_value()
def __iter__(self):
return self
def next(self):
if next_value == terminating_value:
raise StopIteration()
return next_value
这篇关于如何立即运行生成器函数的初始化代码,而不是在第一次调用时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何立即运行生成器函数的初始化代码,而不是在第一次调用时?


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01