让函数在循环中只执行一次的有效方法 [英] Efficient way of having a function only execute once in a loop
问题描述
目前,我正在做类似以下的事情,这变得很乏味:
At the moment, I'm doing stuff like the following, which is getting tedious:
run_once = 0
while 1:
if run_once == 0:
myFunction()
run_once = 1:
我猜有一些更被接受的方法来处理这些东西吗?
I'm guessing there is some more accepted way of handling this stuff?
我正在寻找的是让函数按需执行一次.例如,按下某个按钮.它是一个交互式应用程序,有很多用户控制的开关.为每个开关设置一个垃圾变量,只是为了跟踪它是否已运行,似乎效率低下.
What I'm looking for is having a function execute once, on demand. For example, at the press of a certain button. It is an interactive app which has a lot of user controlled switches. Having a junk variable for every switch, just for keeping track of whether it has been run or not, seemed kind of inefficient.
推荐答案
我会在函数上使用装饰器来跟踪它运行的次数.
I would use a decorator on the function to handle keeping track of how many times it runs.
def run_once(f):
def wrapper(*args, **kwargs):
if not wrapper.has_run:
wrapper.has_run = True
return f(*args, **kwargs)
wrapper.has_run = False
return wrapper
@run_once
def my_function(foo, bar):
return foo+bar
现在 my_function
将只运行一次.对它的其他调用将返回 None
.如果您希望它返回其他内容,只需在 if
中添加一个 else
子句即可.根据您的示例,它不需要返回任何内容.
Now my_function
will only run once. Other calls to it will return None
. Just add an else
clause to the if
if you want it to return something else. From your example, it doesn't need to return anything ever.
如果您不控制函数的创建,或者函数需要在其他上下文中正常使用,您也可以手动应用装饰器.
If you don't control the creation of the function, or the function needs to be used normally in other contexts, you can just apply the decorator manually as well.
action = run_once(my_function)
while 1:
if predicate:
action()
这将使 my_function
可用于其他用途.
This will leave my_function
available for other uses.
最后,如果你只需要运行一次两次,那么你就可以了
Finally, if you need to only run it once twice, then you can just do
action = run_once(my_function)
action() # run once the first time
action.has_run = False
action() # run once the second time
这篇关于让函数在循环中只执行一次的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!