我不知道如何将原始参数传递给堆叠的装饰器。这是我的示例:
def outside_decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
print('outside args:',inspect.getfullargspec(function).args)
return function(*args,**kwargs)
return wrapper
def inside_decorator(function):
@functools.wraps(function)
def innerwrapper(*args,**kwargs):
print('inside args:', inspect.getfullargspec(function).args)
return function(*args,**kwargs)
return innerwrapper
class trial:
@outside_decorator
@inside_decorator
def __init__(self,val1,val2,val3,note1='hello',note2='hi'):
print('decorated function args:',inspect.getfullargspec(trial).args)
print('arg values:',val1, val2, val3, note1, note2)
a=trial(1,2,3)
输出为:
outside args: []
inside args: ['self', 'val1', 'val2', 'val3', 'note1', 'note2']
decorated function args: []
arg values: 1 2 3 hello hi
[我已经看到一些答案,它们引用@functools.wraps()
出错,并使用@decorator.decorator
涉及装饰器模块来装饰装饰器,但是这样做是为了使装饰器或包装器仅接受位置参数输入。我已经尝试了每种组合,但无法对此做出正面或反面。
如何通过堆叠的修饰符保留参数?
这是一个很好的示例,说明了如何在Python的装饰器中使用参数:https://www.geeksforgeeks.org/decorators-with-parameters-in-python/
[请记住,一切都是Python中的对象,当您尝试用Python中的另一个函数来装饰一个函数时,这意味着您只是将内部函数用作外部函数的参数。