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()的调用方式

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

  • 相关阅读:
    (转载)_信息安全入门指南
    经历--比赛绿盟_安全研究员
    Python正则表达式操作指南
    web 安全学习
    2014-9-10中午睡觉的一个梦
    渗透工具学习
    CVE 2013-3897
    STL 学习
    设置chrome 可以保存mht网页
    合并windows7系统下的两个IE8浏览器进程
  • 原文地址:https://www.cnblogs.com/pythonbz/p/6283999.html
Copyright © 2011-2022 走看看