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

本文详细介绍了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就是一个闭包。

 

转载于:https://www.cnblogs.com/lixinliang/p/8409421.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值