我有一个功能-
def add(a, b):
return a+b
现在我希望它使用装饰器将 100 添加到结果中 -
@decorator(100)
def add(a, b):
return (a+b)
class decorator():
def __init__(self, c):
self.c = c
def __call__(self, f):
def _wrapped_f(a, b):
return self.c + f(a, b)
return _wrapped_f
问题是当我想保留额外的参数变量而不是固定为 100 时。
有点像 -
@decorator(c)
def add(a, b):
return (a+b)
我可以在函数调用期间以某种方式分配这个变量的值吗? (调用添加函数时) 我想使用装饰器执行此操作的原因是因为我不想修改我的函数添加。
我负担不起函数中的额外参数,例如 -
def(a, b, c=0):
return (a+b+c)
因此,需要装饰器。
最佳答案
当然。装饰器所做的就是用包装版本替换原始函数;该包装器可以接受任意数量的参数。
我不确定您为什么要使用类 - 作为标准装饰器,这会更清楚。
def decorator(func):
def wrapped(a, b, c):
return c + func(a, b)
return wrapped
@decorator
def add(a, b):
return (a+b)
关于python - 一些函数参数可以通过装饰器传递吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35598970/