在 python 中仅使用一个装饰器使用定义的属性并将 n 个属性传递给包装器
Use defined attributes and passing n number of attributes to wrapper using only one decorator in python
我正在学习使用装饰器,但我不知道如何在不制作特定于功能的装饰器的情况下将已经定义的属性传递给包装器。
假设我有一个装饰器:
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))
?因为这会让我无法定义任何属性。这是我唯一的克制。
谢谢。
包装器必须接受参数(因为它替换了绑定到修饰名称的原始函数),并且这些参数必须传递给 func
.
def decorator(func):
def wrapper(<b>*args, **kwargs</b>):
print("Before the function")
func(<b>*args, **kwargs</b>)
print("After the function")
return wrapper
我正在学习使用装饰器,但我不知道如何在不制作特定于功能的装饰器的情况下将已经定义的属性传递给包装器。
假设我有一个装饰器:
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))
?因为这会让我无法定义任何属性。这是我唯一的克制。
谢谢。
包装器必须接受参数(因为它替换了绑定到修饰名称的原始函数),并且这些参数必须传递给 func
.
def decorator(func):
def wrapper(<b>*args, **kwargs</b>):
print("Before the function")
func(<b>*args, **kwargs</b>)
print("After the function")
return wrapper