检查函数参数的装饰器
decorator that check the args of a function
我需要为一个函数创建装饰器,这样如果一个特定的函数用相同的参数连续调用两次,它就不会 运行,return None相反。
被装饰的函数可以有任意数量的参数,但不能有关键字参数。
例如:
@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
看看这个简单的方法是否适合你。
prev_arg = ()
def dont_run_twice(myPrint):
def wrapper(*args):
global prev_arg
if (args) == prev_arg:
return None
else:
prev_arg = (args)
return myPrint(*args)
return wrapper
@dont_run_twice
def myPrint(*args):
print(*args)
def filter_same_args(func):
args_store = set()
def decorator(*args):
if args in args_store:
return None
args_store.add(args)
func(*args)
return decorator
@filter_same_args
def my_print(*args):
print(*args)
my_print('one', 'two', 3)
my_print('one', 'two', 3)
my_print('one', 'two', 3, 4)
我需要为一个函数创建装饰器,这样如果一个特定的函数用相同的参数连续调用两次,它就不会 运行,return None相反。
被装饰的函数可以有任意数量的参数,但不能有关键字参数。
例如:
@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
看看这个简单的方法是否适合你。
prev_arg = ()
def dont_run_twice(myPrint):
def wrapper(*args):
global prev_arg
if (args) == prev_arg:
return None
else:
prev_arg = (args)
return myPrint(*args)
return wrapper
@dont_run_twice
def myPrint(*args):
print(*args)
def filter_same_args(func):
args_store = set()
def decorator(*args):
if args in args_store:
return None
args_store.add(args)
func(*args)
return decorator
@filter_same_args
def my_print(*args):
print(*args)
my_print('one', 'two', 3)
my_print('one', 'two', 3)
my_print('one', 'two', 3, 4)