• 【Python 学习_第4周_字符编码】金角大王培训_第4周_理解装饰器_1


         一、装饰器定义

       第一次使用装饰器是在编写网页测试脚本时,unittest自带的 skip装饰器,用于确定是否执行此测试用例,后期就感觉装饰器这个东西很难懂,听完老师讲课,发现是没有理解装饰器的特点和功能,我简单复述下老师讲的装饰器。装饰的对象为函数,装饰后的函数比装饰前的函数增加了功能,但函数代码未改动,且调用方式不变。

         二、只包含函数形参装饰器代码编写

              下面以函数定义的形式讲解装饰器

           1.若装饰器不采用嵌套函数,仅为单层函数,由于不能改变原来函数的调用方式,采用单层函数需返回 形式参数地址。

    import time
    
    def decorator_1(fun):
        time_start = time.time()
        fun()
        time_end = time.time()
        time_du = time_end - time_start
        print (time_du)
        return fun
    
    @decorator_1 #此代码功能等效于 decorator_1(dece)
    def dece():
        time.sleep(3)
        print('in the test_1')
    
    dece()


    执行结果为:

    in the test_1
    3.0
    in the test_1

    从执行结果,说明dece()函数执行了两次。分析下代码原因为:

    程序中执行dece() 代码等同于执行

    dece = decorator_1(dece)

    dece()

    而在函数decorator_1中的语句fun() 代表执行一次 传入decorator_1的函数,说明dece函数执行一次;decorator_1的返回值为dece地址,因此dece()语句使得dece函数执行两次。

    从以上函数说明装饰器不可以为单层函数,且装饰器函数返回值不可以为 函数形参的地址

      2 .装饰器2层嵌套结构

         由于返回值不能为形式参数地址,还要求 调用方式不变,可以将装饰器返回到另外函数中,在此函数中 执行被装饰的函数,得到的代码如下:

    import time
    
    def decorator_1(fun):
        def in_decorator_1():
            time_start = time.time()
            fun()
            time_end = time.time()
            time_du = time_end - time_start
            print (time_du)
        return in_decorator_1
    
    
    @decorator_1
    def dece():
        time.sleep(3)
        print('in the test_1')
    
    dece()
     
    执行结果为:
    in the test_1
    3.0

    满足要求。

        三 .小结

             只是包含函数形参的装饰器为嵌套函数,包含两层函数,其中内层函数运行被装饰函数,外层函数返回值为内层函数。用于需要增加被修饰函数功能,又不能修改被修饰函数代码的场景。应用方法为:

    @装饰器名称

    被装饰的函数定义

     

     

     

        

     

     

  • 相关阅读:
    (转)es进行聚合操作时提示Fielddata is disabled on text fields by default
    (转)Elasticsearch分析聚合
    搜索引擎-倒排索引基础知识(摘自《这就是搜索引擎:核心技术详解》)
    Elasticsearch5.x Head插件安装
    Java开发规范总结
    (转)ElasticSearch Java Api-检索索引库
    QTGraphics-View拖拽以及鼠标指针操作
    Qt Graphics-View的打印功能实现
    Qt使用QPainter绘制矢量图并保存为svg文件
    QT制作一个位图画图板程序
  • 原文地址:https://www.cnblogs.com/Finding-bugs/p/9277394.html
Copyright © 2020-2023  润新知