• python 装饰器前之闭包和装饰器


     
    装饰器:
    一, 例如:
    # vim yue7.py
    def foo():
      print ("fool-------------------")
    
    foo()
    
    运行:
    [root@localhost python]# python yue7.py
    fool-------------------
    
    二,要求:要在上述函数不改变函数调用方式的情况下增加代码运行的时间。
    
    # yue6.py
    import time
    
    def show_time(f):
      def inner():                   #条件1:内部函数;
        start = time.time()    
        f()                               #条件2:对外部环境的引用 foo()
        end = time.time()
        print ("Spend --%s s ---" %(end-start))
      return inner
    
    def foo():
      print ("fool-------------------")
      time.sleep(2)
    
    foo = show_time(foo)      #<function show_time.<locals>.inner at 0x7f1686630488>  (此时的foo只是一个内存地址)
    foo()              
    
    
    运行结果:
    
    [root@localhost python]# python yue6.py
    fool-------------------
    Spend --2.0029256343841553 s ---
    
    
    三,对上面的代码进行改进,用装饰器修饰。
    
    # vim  yue5.py
    
    import time
    
    def show_time(f):
      def inner():
        start = time.time()
        f()
        end = time.time()
        print ("Spend --%s s ---" %(end-start))
      return inner
    
    @show_time            #foo = show_time(foo)(装饰器)
    def foo():
      print ("fool-------------------")
      time.sleep(2)
    
    foo()     #调用
    
    运行结果:
    [root@localhost python]# python yue5.py
    fool-------------------
    Spend --2.00250244140625 s ---
    
    

     四,闭包:


    #
    vim yue4.py def outer(): x = 10 def inner(): #条件1: inner是内部函数,相对于outer函数来说; print (x) #条件2:print(x)是对外部环境变量x=10的引用; return inner #outer()() f = outer() f() [root@localhost python]# python yue4.py 10 结论:内部函数inner就是一个闭包。
  • 相关阅读:
    block: cfq 学习01
    SAS,SATA普及文档
    如何查看盘的类型
    [转载] Linux Futex的设计与实现
    C++ std::map的安全遍历并删除元素的方法
    我的vimrc配置
    .vimrc
    RC: blkio throttle 测试
    LTTng
    基于ADL5317的雪崩光电二极管(APD)偏压控制/光功率监测电路的设计
  • 原文地址:https://www.cnblogs.com/lixinliang/p/8409421.html
Copyright © 2020-2023  润新知