python - 一些函数参数可以通过装饰器传递吗?

标签 python function python-decorators

我有一个功能-

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/

相关文章:

javascript - 是否可以使用网站的 url 在网站上运行 javascript 函数?

python - Matplotlib制作几个图形并使用箭头改变 - Python

python - 我怎样才能让 python 脚本安全地退出?

python - 在 python 中屏蔽然后粘贴两个图像

function - 在lua中组合两个函数

python - 如何将一维 ndarray 列表转换为二维 ndarray (mxnet ndarray)

swift - 值类型变量在传递给函数时如何被复制,这个副本是什么?

python-3.x - 在 MyPy 中使用 TypeVar 输入带参数的装饰器会产生预期的无人居住类型

python - 使用装饰器处理函数参数