首页 > 解决方案 > 在python中仅使用一个装饰器使用定义的属性并将n个属性传递给包装器

问题描述

我正在学习使用装饰器,但我不知道如何在不制作特定于函数的装饰器的情况下将已定义的属性传递给包装器。

假设我有一个装饰器:

def decorator(func):
    def wrapper():
        print("Before the function")
        func()
        print("After the function")

    return wrapper

有了这个,我只能将它与只有定义属性或没有任何属性的函数一起使用,例如:

@decorator
def foo1(attribute1=10, attribute2=20):
    print(attribute1, attribute2)
    return

foo1()

但这让我无法运行:

foo1(1, 2)

有了这个问题,我也不能在没有相同数量的属性设置的不同函数上使用这个装饰器。

因此,有一种方法可以解决这个问题,而无需使用*args**kwargs或至少无需调用如下所示的函数:foo((arg1, arg2, argn))?因为它会让我无法定义任何属性。这是我唯一的约束。

谢谢。

标签: pythonpython-3.xattributeswrapperpython-decorators

解决方案


包装器必须接受参数(因为它替换了绑定到修饰名称的原始函数),并且这些参数必须传递给func.

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before the function")
        func(*args, **kwargs)
        print("After the function")

    return wrapper

推荐阅读