在 Python 中是否可以向带有装饰器的函数添加参数?

Is it possible to add a parameter to a function with a decorator in Python?

所以我尝试编写一个装饰器函数来保护对具有“密码字符串”的函数的访问auth。装饰器函数如下所示:

from functools import wraps

def decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if "auth" in kwargs.keys():
            if kwargs["auth"] == "12345":
                func(*args, **kwargs)
                return
        print("Not authorized.")

    return wrapper

我想要保护的示例函数的定义如下所示:

@decorator
def add(list, elem, auth):
    list.append(elem)

在我的主要代码中,我这样调用 add()

def main():
    lst = [3,5]
    add(lst, 2, auth="12345")
    print(lst)


if __name__ == "__main__":
    main()

我的目标是能够做到这一点,而无需在 add() 的定义中明确提及 auth,所以我可以这样做:

@decorator
def add(list, elem):
    list.append(elem)

这可能吗?

你应该可以得到你想要的:

if kwargs.pop("auth", None) == "12345":

您需要删除 "auth" 参数,因为您正在使用它并且不想将它传递给 child。

你也应该更换

func(*args, **kwargs)
return

return func(*args, **kwargs)

以防您碰巧调用了一个 returns 值的函数。