[英]Use defined attributes and passing n number of attributes to wrapper using only one decorator in python
I am learning to use decorators and I can't figure out how to pass already defined attributes to the wrapper without making a function specific decorator.我正在学习使用装饰器,但我无法弄清楚如何在不制作特定于功能的装饰器的情况下将已定义的属性传递给包装器。
Let's say I have a decorator :假设我有一个装饰器:
def decorator(func):
def wrapper():
print("Before the function")
func()
print("After the function")
return wrapper
With this I am only able to use it with functions with only defined attributes or without any attribute like :有了这个,我只能将它与仅具有定义属性或没有任何属性的函数一起使用,例如:
@decorator
def foo1(attribute1=10, attribute2=20):
print(attribute1, attribute2)
return
foo1()
But it makes me unable to run :但这让我无法运行:
foo1(1, 2)
With this problem, I also can't use this decorator on different functions that don't have the same amount of attributes to set.对于这个问题,我也不能在没有相同数量的属性设置的不同函数上使用这个装饰器。
So, it there a way to fix this problem without the use of *args
and **kwargs
or at least without having to call a function that would look like this : foo((arg1, arg2, argn))
?那么,有没有一种方法可以在不使用*args
和**kwargs
情况下解决这个问题,或者至少不必调用如下所示的函数: foo((arg1, arg2, argn))
? Because it would make me unable to define any attribute.因为这会让我无法定义任何属性。 This is my only restrain.这是我唯一的克制。
Thanks.谢谢。
The wrapper has to accept arguments (because it replaces the original function bound to the decorated name), and those arguments have to be passed to func
.包装器必须接受参数(因为它替换了绑定到修饰名称的原始函数),并且这些参数必须传递给func
。
def decorator(func):
def wrapper(*args, **kwargs):
print("Before the function")
func(*args, **kwargs)
print("After the function")
return wrapper
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.