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就是一个闭包。

 

posted @ 2018-02-03 14:36  lixinliang  阅读(200)  评论(0编辑  收藏  举报