zoukankan      html  css  js  c++  java
  • 装饰器

    装饰器:本质是函数,作用是为其他函数添加附加功能

    原则:

    1.不改变被装饰函数的源代码

    2.不改变被装饰函数的调用方式

    实现装饰器需要先实现那些功能呢?

    1.函数就是“变量”,将函数体赋予函数名,就可以在内存中存在了

    # def dec():
    #     print('this is dec')
    #     bar()
    # def bar():
    #     print('this is bar')
    # dec()

    def bar():

        print('this is bar')
    def dec():
        print('this is dec')
        bar()
    dec()

     

    上图表示:

    两个函数体都赋予了函数名,只要dec()调用,就都可以实现函数体,表明了函数是需要被赋予“变量”才可以实现的

    2.高阶函数

    a.把一个函数名当实参传递给另一个函数

    b.返回值中包含函数名(不修改函数的调用方式)

    import time
    def bar():
        time.sleep(3)
        print('this is bar')
    def test(func):
        start_time=time.time()
        func()
        stop_time=time.time()
        print('this is difference time is %s'%(stop_time-start_time))
    test(bar)

    上述的例子中,通过test(bar)bar函数名传递到test函数中,开始运行函数体,由于func=bar,因此,bar()也可以写成func()的调用方式

    提供了一种思路:再不修改源代码的情况下,为函数添加功能

  • 相关阅读:
    Bootstrap的介绍和响应式媒体查询
    jquery内容补充
    jquery的ajax
    jquery的事件
    JQuery的筛选方法
    jquery的css
    jQuery的文档操作
    操作表单域中的value值
    jquery的属性操作
    jquery的效果
  • 原文地址:https://www.cnblogs.com/pythonbz/p/6283999.html
Copyright © 2011-2022 走看看