• 012.Python基础--装饰器深入


    多个装饰器的用法:

    装饰器的调用顺序:与@装饰名 出现的顺序相反,越后出现越先执行

    装饰器是可叠加使用的

    实现两个装饰器的实例:

    import time
    def deco01(x):
        def wrapper(*args, **kwargs):
            print("this is deco01")
            start_time = time.time()
            x(*args, **kwargs)
            end_time = time.time()
            execution_time = (end_time - start_time)*1000
            print("time is %d ms" % execution_time)
            print("deco01 end here")
        return wrapper
    
    def deco02(x):
        def wrapper(*args, **kwargs):
            print("this is deco02")
            x(*args, **kwargs)
    
            print("deco02 end here")
        return wrapper
    
    @deco01
    @deco02
    def f(a,b):
        print("be on")
        time.sleep(1)
        print("result is %d" %(a+b))
    
    if __name__ == '__main__':
        f(3,4)

    f(a,b)先被deco02装饰 再被deco01装饰

    得到结果如下:

    参数传递:

    两类:

      固定参数的装饰器

      无固定参数的装饰器

    固定参数:

    import time
    def deco(x):
        def wrapper(a,b):
            start_time = time.time()
            x(a,b)
            end_time = time.time()
            execution_time = (end_time - start_time)*1000
            print("time is %d ms" % execution_time)
        return wrapper
    @deco
    def f(a,b):
        print("be on")
        time.sleep(1)
        print("result is %d" %(a+b))
    
    if __name__ == '__main__':
        f(3,4)

    无固定参数:

    def deco(x):
        def wrapper(*args, **kwargs):
            start_time = time.time()
            x(*args, **kwargs)
            end_time = time.time()
            execution_time = (end_time - start_time)*1000
            print("time is %d ms" %execution_time)
        return wrapper
    @deco
    def f(a,b):
        print("be on f1")
        time.sleep(1)
        print("result is %d" %(a+b))
    @deco
    def f2(a,b,c):
        print("be on f2")
        time.sleep(1)
        print("result is %d" %(a+b+c))
    
    if __name__ == '__main__':
        f2(3,4,5)
        f(3,4)

    f2()  和 f()  都被装饰

  • 相关阅读:
    第一个Struts1步骤
    struts框架学习过程中的问题
    struts2笔记
    搭建struts2框架
    一个系统钩子
    TMemIniFile 与TIniFile 区别
    rc4加密
    注册dll
    delphi 功能函数大全-备份用
    VC中文件路径问题
  • 原文地址:https://www.cnblogs.com/zhouA/p/14506214.html
Copyright © 2020-2023  润新知