防止函数连续被调用两次 [英] Prevent a function from being called twice in a row
本文介绍了防止函数连续被调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习装饰器,我有一个任务要求我创建一个装饰器,以防止某个函数连续两次被调用。如果再次调用相同的函数,它将返回None
我似乎无法理解它的真正工作原理,到目前为止,我已经实现了:
I'm learning decorators and I have a task asking me to create a decorator to prevent a function from being called twice in a row. If the same function is called again, it should return None I can't seem to understand how it really works, so far I've achieved this:
def dont_run_twice(f):
global counter
def wrapper(*args, **kwargs):
counter += 1
if counter == 2:
return None
else:
result = f(*args, **kwargs)
return result
counter = 0
(我知道这是一次非常糟糕的尝试,但我只是不知道跟踪带有特定参数的函数以检查其是否已经存在的方法)
输出应类似于:
(I know that it's a really bad attempt, but I just don't know a way to keep track of a function called with specific arguments in order to check if it was already before) the output should be something like:
@dont_run_twice
def myPrint(*args):
print(*args)
myPrint("Hello")
myPrint("Hello") #won't do anything (only return None)
myPrint("Hello") #still does nothing.
myPrint("Goodbye") #will work
myPrint("Hello") #will work
推荐答案
这似乎可以帮助您:
import functools
def do_not_run_twice(func):
prev_call = None
@functools.wraps(func) # It is good practice to use this decorator for decorators
def wrapper(*args, **kwargs):
nonlocal prev_call
if (args, kwargs) == prev_call:
return None
prev_call = args, kwargs
return func(*args, **kwargs)
return wrapper
尝试一下:
my_print("Hello")
my_print("Hello") # won't do anything (only return None)
my_print("Hello") # still does nothing.
my_print("Goodbye") # will work
my_print("Hello") # will work.
这篇关于防止函数连续被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文