Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用定义的属性,并在python中仅使用一个decorator将n个属性传递给包装器_Python_Python 3.x_Attributes_Wrapper_Python Decorators - Fatal编程技术网

使用定义的属性,并在python中仅使用一个decorator将n个属性传递给包装器

使用定义的属性,并在python中仅使用一个decorator将n个属性传递给包装器,python,python-3.x,attributes,wrapper,python-decorators,Python,Python 3.x,Attributes,Wrapper,Python Decorators,我正在学习使用decorator,我不知道如何将已经定义的属性传递给包装器,而不使用特定于函数的decorator 假设我有一个装饰师: def decorator(func): def包装器(): 打印(“函数前”) func() 打印(“函数后”) 返回包装器 有了它,我只能将其用于只定义了属性或没有任何属性的函数,如: @decorator def foo1(属性1=10,属性2=20): 打印(属性1、属性2) 返回 foo1() 但这让我无法跑步: foo1(1,2) 对于这个问

我正在学习使用decorator,我不知道如何将已经定义的属性传递给包装器,而不使用特定于函数的decorator

假设我有一个装饰师:

def decorator(func):
def包装器():
打印(“函数前”)
func()
打印(“函数后”)
返回包装器
有了它,我只能将其用于只定义了属性或没有任何属性的函数,如:

@decorator
def foo1(属性1=10,属性2=20):
打印(属性1、属性2)
返回
foo1()
但这让我无法跑步:

foo1(1,2)
对于这个问题,我也不能在没有相同数量属性设置的不同函数上使用这个装饰器

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


谢谢。

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

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

    return wrapper
def decorator(func):
def包装(*args,**kwargs):
打印(“函数前”)
func(*args,**kwargs)
打印(“函数后”)
return wrapper
注意,“属性”是对象上的东西,例如
list.sort
。这里有参数(传递给函数的内容,例如
foo1(1,2)
)中的
1,2
)和参数(函数接收的内容,例如
def foo(a,b):…
)中的
a,b
)。