【问题标题】:How to change a function's return using a decorator?如何使用装饰器更改函数的返回值?
【发布时间】:2011-11-04 07:52:34
【问题描述】:

我想创建一个装饰器来像这样更改函数的返回值,如何做到这一点?:

def dec(func):
    def wrapper():
        #some code...
        #change return value append 'c':3
    return wrapper

@dec
def foo():
    return {'a':1, 'b':2}

result = foo()
print result
{'a':1, 'b':2, 'c':3}

【问题讨论】:

    标签: python decorator


    【解决方案1】:

    我将在这里尽量笼统地说,因为这可能是一个玩具示例,您可能需要一些参数化的东西:

    from collections import MutableMapping
    
    def map_set(k, v):
        def wrapper(func):
            def wrapped(*args, **kwds):
                result = func(*args, **kwds)
                if isinstance(result, MutableMapping):
                    result[k] = v 
                return result
            return wrapped
        return wrapper
    
    @map_set('c', 3)
    def foo(r=None):
        if r is None:
            return {'a':1, 'b':2}
        else:
            return r
    
    >>> foo()
    {'a': 1, 'c': 3, 'b': 2}
    
    >>> foo('bar')
    'bar'
    

    【讨论】:

    • 是的!它有效。还有更多你添加了一个 mutableMapping 检查。太棒了。
    【解决方案2】:

    嗯....你调用装饰函数并更改返回值:

    def dec(func):
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            result['c'] = 3
            return result
        return wrapper
    

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 2020-04-28
      • 1970-01-01
      • 2022-08-15
      • 2015-01-09
      • 2019-10-05
      相关资源
      最近更新 更多