python装饰器 - 修改函数返回值

def f(n):
    n+=1
    print("hello :{}".format(n))
    return n+1

ret = f(9)
print("Functionreturn value :",ret)

在没有装饰器的情况下,运行结果如下

hello :10
Functionreturn value : 11

现在我们给它加上装饰器修改他的返回值

def deco(fun):
    def f(n):
        print("deco start ")
        ret=fun(n)
        print("deco end:{} ".format(ret))
        return ret+10000
    return f

@deco
def f(n):
    n+=1
    print("hello :{}".format(n))
    return n+1

ret = f(9)
print("Functionreturn value :",ret)

运行结果如下

deco start 
hello :10
deco end:11 
Functionreturn value : 10011

函数返回值成功被修改

posted @ 2022-11-24 15:34  腹肌猿  阅读(212)  评论(0编辑  收藏  举报