2011-08-26 104 views
6

我想创建一个装饰来改变这样的一个函数的返回值,如何做到这一点像下面?:如何用python中的装饰器修改函数的返回值?

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} 

回答

21

嗯....你叫装饰功能和改变返回值:

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

我会尽量相当普遍的在这里,因为这可能是一个玩具例子,你可能需要一些参数:

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' 
+0

是的!它的工作。更多的你添加一个mutableMapping检查。它是很大的。 – libaoyin