【发布时间】:2021-11-21 06:09:20
【问题描述】:
我已经准备了一些函数装饰器,从装饰器的角度传递了默认参数:
def decorator_wraper(max_repeating=20)
def decorator(function):
def wrap_function(*args, **kwargs):
print(f"max_repeating = {max_repeating}")
repeat = 0
while repeat < max_repeating:
try:
return function(*args, **kwargs)
break
except Exception:
pass
repeat += 1
return wrap_function
return decorator
它工作正常,所以如果某个装饰函数失败 - 装饰器允许重复该函数直到成功或重复 >= max_repeating。
但是如果我需要从修饰函数的角度更改默认的 max_repeating 怎么办?
这里我有两个装饰函数:
@decorator_wraper(5)
def decorate_me_with_argument(max_repeating=10):
print('decorate_me_with_argument')
@decorator_wraper()
def decorate_me_with_default():
print('decorate_me_with_default')
calling:
decorate_me_with_argument() # max_repeating should be 5 cause while decorating the function I have passed 5.
decorate_me_with_default() # max repeating should be 20 cause default for the decorator is 20.
以及我想要达到的目标:
decorate_me_with_argument(3) # max_repeating should be 3
decorate_me_with_default(8) # max repeating should be 8
也许有什么简单的方法可以解决这样的问题?
【问题讨论】:
-
您传递给
decorate_me_with_argument的任何参数现在都将转到wrap_function,如果包装后的function也接受参数怎么办? -
我已将所有参数强制为 key-args,它对我有用。 (我的意思是big_bad_bison提出的解决方案)也许你有更好的解决方案?