多个装饰器,装饰一个函数

def w1(fune):
    print("---日志1----")
    def net1():
        print("-----调用1-----")
        fune()
        print("结束")

    return net1


def w2(fune):
    print("----日志2----")
    def net2():
        print("---调用2----")
        fune()

    return net2


@w1  # f1=w1(net2)
@w2  # f1=w2(f1)
def f1():
    print("----3----")



a = f1()
print(a)

# 装饰过程,先装饰w2,返回 net2引用,f1=net2 又因为外层还有一层装饰,
# 所以 外层装饰@w1又将net2 当参数传入,则为 f1=w1(net2),fune=net2,返回net1函数的引用给f1 (f1=net1).这样装饰结束

# 调用过程,因为调用f1(),则调用函数net1,又因为net1函数中调用fune(fune=net2),则调用net2,然后依次调用f1()
运行结果

----日志2----
---日志1----
-----调用1-----
---调用2----
----3----
结束

None

根据运行结果,可分析出,先装饰@w2 在装饰 @w1 ,当调用f1()时,则先调用@w1


你可能感兴趣的:(多个装饰器,装饰一个函数)