zoukankan      html  css  js  c++  java
  • Python函数(八)-装饰器(一)

    装饰器通过函数来定义,用来装饰函数

    装饰器的结构为高阶函数和内嵌函数

    装饰器不改变被装饰函数的源代码和运行方式

    如何实现这个效果呢?

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    import time
    
    def timer(func): #定义一个装饰器
        def deco():
            start_time = time.time()
            func()
            stop_time = time.time()
            print("the run time is %s"%(stop_time-start_time))
        return deco
    
    def test1():
        time.sleep(3)
        print('in the test1')
    
    test1 = timer(test1)
    test1()
    

    既没有改变被装饰函数的源代码,也没有改变它的运行方式

    运行

    这么写有些复杂,可以直接在函数前调用装饰器

    调用装饰器的格式为:@装饰器名

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    import time
    
    def timer(func): #定义一个装饰器
        def deco():
            start_time = time.time()
            func()
            stop_time = time.time()
            print("the run time is %s"%(stop_time-start_time))
        return deco
    
    @timer #相当于test1 = timer(test1)
    def test1():
        time.sleep(3)
        print('in the test1')
    
    test1()
    

    运行

    执行过程:

    先走test1函数前的装饰器timer(),然后在timer()函数内走函数deco(),记录下start_time,然后deco()函数调用函数test1(),然后执行完函数test1()后,记录下stop_time,最后计算时间并打印

    虽然装饰器不会修改被装饰函数的源代码和运行方式,但是不能直接返回函数的返回值

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    import time
    
    def timer(func): #定义一个装饰器
        def deco():
            start_time = time.time()
            func()
            stop_time = time.time()
            print("the run time is %s"%(stop_time-start_time))
        return deco
    
    @timer #test1 = timer(test1)
    def test1():
        time.sleep(3)
        print('in the test1')
        return "test1"
    
    print(test1())
    

    运行结果

    打印的返回值为None,因为这个返回值为装饰器里的内嵌函数的返回值

    如果需要打印被装饰函数的返回值的话,需要在装饰器里的内嵌函数中返回

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    import time
    
    def timer(func): #定义一个装饰器
        def doc():
            start_time = time.time()
            func()
            stop_time = time.time()
            print("the run time is %s"%(stop_time-start_time))
            return func()
        return doc
    
    @timer #test1 = timer(test1)
    def test1():
        time.sleep(3)
        print('in the test1')
        return "test1"
    
    print(test1())
    

    运行结果

  • 相关阅读:
    用数据管理过程(2)——通过经验值管理项目
    用数据管理过程(3)——可预测级别的量化管理(麦当劳的管理方式)
    JMeter对Oracle数据库进行压力测试
    [置顶] Linux下的截图小工具
    [互联网面试笔试汇总C/C++-7] 寻找两个链表的第一个交点-微策略
    使用 OpenSSL API 进行安全编程
    带外数据的接收与发送
    oracle本月、上月、去年同月第一天最后一天
    mysql查看权限的命令
    php的一个验证邮箱的正则表达式
  • 原文地址:https://www.cnblogs.com/sch01ar/p/8401711.html
Copyright © 2011-2022 走看看