【问题标题】:What is happening to the function arguments with stacked python decorators?带有堆叠 python 装饰器的函数参数发生了什么?
【发布时间】:2020-05-15 07:33:39
【问题描述】:

我不知道如何将原始参数传递给堆叠的装饰器。这是我的例子:

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 的装饰器模块来装饰装饰器,但它使装饰器或包装器只允许位置参数输入。每种组合我都试过了,但我无法判断它的正面或反面。

如何通过堆叠装饰器保留参数?

【问题讨论】:

  • 我不确定你的意思。你的装饰者不接受任何争论。如果你去掉那个inspect...,只打印argskwargs,你可以看到你已经可以访问args了。
  • 你想做什么?您是否意识到装饰器只是将函数作为参数,所以您的trial.__init__() 方法实际上是outside_decorator(inside_decorator(trial.__init__(*args, **kwargs)))

标签: python arguments decorator wrapper python-3.7


【解决方案1】:

这是一个很好的例子,如何在 Python 的装饰器中使用参数: https://www.geeksforgeeks.org/decorators-with-parameters-in-python/

请记住,在 Python 中一切都是对象,当您尝试用 Python 中的另一个函数装饰一个函数时,这意味着您只是将内部函数用作外部函数的参数。

【讨论】:

    猜你喜欢
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 2014-12-16
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多