![](/img/trans.png)
[英]Using class attributes to modify a docstring with a decorator in Python
[英]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(*args, **kwargs):
print("Before the function")
func(*args, **kwargs)
print("After the function")
return wrapper
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.