2017-10-09 54 views
-3

我对装饰器比较新。传递函数的返回值给装饰器

我的疑惑是我们可以将函数的返回值传递给装饰器函数。添加伪代码

@dec(a = x) 
def fun(): 
    x = 25 
    return x 
# My decorator function 
def dec(a = x) 
    print a 
+0

这我不清楚你想要做什么。这目前不起作用,对吧?但它应该如何工作? – MSeifert

+0

是的,这不起作用。我需要将函数的返回值传递给装饰器函数。可能吗 ?? – taz

+0

当然,请参阅示例https://stackoverflow.com/questions/7201715/how-change-a-functions-return-with-decorator-in-python – MSeifert

回答

0

我猜你正在尝试做这样的事情:

# My decorator function 
def dec(func): 
    def func_wrapper(a): 
     print (a, " :Decorator value a") 
     return func(a) 
    return func_wrapper 

@dec 
def func(a): 
    x = 25 
    print(x, " :Function value x") 
    return x 


func(5) 
# Output: 
# 5 :Decorator value a 
# 25 :Function value x 
相关问题