【问题标题】:How to obtain tuple values from inside of decorator functions in Python如何从 Python 中的装饰器函数内部获取元组值
【发布时间】:2020-12-30 01:27:37
【问题描述】:

我正在探索 Python 中的装饰器函数。我的目标是从装饰器函数内部的包装函数返回一个元组,当传递给装饰器函数的原始函数也返回一个元组时。我的代码 sn-p 粘贴在下面:

def decorator_function(original_function):

    def wrapper_function(*args, **kwargs):
        s, o = original_function(*args, **kwargs)
        return s, o

    return wrapper_function


def test_function(name, command):
    status = True
    output = dict()
    output['message'] = command + " " + name
    return status, output


decorator_func_var = decorator_function(test_function("Kaushik", "Hello"))
ok, out = decorator_func_var()
print(ok)
print(out)

但是,当我执行此操作时,我收到如下错误消息:

我很想知道我的代码 sn-p 哪里出了问题,以及在调用修饰函数时如何获取元组值。如果有任何建议或反馈,我将不胜感激。

【问题讨论】:

    标签: python python-decorators


    【解决方案1】:

    你的装饰器接受一个函数作为参数,并返回一个函数。你只是想要

    ok, out = decorator_function(test_function)("Kaushik", "Hello")
    

    或者更清楚一点:

    wrapped_function = decorator_function(test_function)
    ok, out = wrapped_function("Kaushik", "Hello")
    

    【讨论】:

    • 非常感谢。那行得通。感谢您的反馈。
    【解决方案2】:
    def decorator_function(original_function):
    
        def wrapper_function(*args, **kwargs):
            s, o = original_function(*args, **kwargs)
            return s, o
    
        return wrapper_function
    
    
    def test_function(name, command):
        status = True
        output = dict()
        output['message'] = command + " " + name
        return status, output
    
    
    decorator_func_var = decorator_function(test_function)
    ok, out = decorator_func_var("Kaushik", "Hello")
    print(ok)
    print(out)
    
    

    你在初始化decorator_func_var之后传参数

    【讨论】:

    • 非常感谢。那行得通。感谢您的反馈。
    猜你喜欢
    • 2018-07-05
    • 1970-01-01
    • 2018-01-21
    • 2017-08-01
    • 2011-12-02
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    相关资源
    最近更新 更多