Python 简明教程 — 22,Python 闭包与装饰器
当你选择了一种语言,意味着你还选择了一组技术、一个社区。
目录

本节我们来详情闭包与装饰器。
闭包与装饰器是函数的高级用法,其实在详情完Python 函数我们即可以详情本节的内容,但因为Python中的类也可以用来实现装饰器,所以我们等到详情完了Python 类再来统一详情闭包与装饰器。
装饰器使用的是闭包的特性,我们先来详情闭包,再来详情装饰器。
1,什么是闭包
Python 的函数内部还允许嵌套函数,也就是一个函数中还定义了另一个函数。如下:
def fun_1(): def fun_2(): return 'hello' s = fun_2() return ss = fun_1()print(s) # 'hello'在上面的代码中,我们在函数fun_1 的内部又定义了一个函数fun_2,这就是函数嵌套。
我们在学习函数的时候,还知道,Python 函数可以作为函数参数和函数返回值。
因而,我们可以将上面代码中的函数fun_2作为函数fun_1的返回值,如下:
def fun_1(): def fun_2(): return 'hello' return fun_2此时,函数fun_1 返回了一个函数,我们这样使用fun_1:
fun = fun_1() # fun 是一个函数s = fun() # 调用函数 funprint(s) # s 就是 'hello'我们再来改进函数fun_1,如下:
def fun_1(s): s1 = 'hello ' + s def fun_2(): return s1 return fun_2上面的代码中,内部函数fun_2返回了变量s1,而s1是函数fun_2的外部变量,这种内部函数能够使用外部变量,并且内部函数作为外部函数的返回值,就是闭包。
编写闭包时都有肯定的套路,也就是,闭包需要有一个外部函数包含一个内部函数,并且外部函数的返回值是内部函数。
2,用闭包实现一个计数器
我们来实现一个计数器的功能,先写一个框架,如下:
def counter(): # 定义内部函数 def add_one(): pass # 返回内部函数 return add_one再来实现计数的功能,如下:
def counter(): # 用于计数 l = [0] # 定义内部函数 def add_one(): l[0] += 1 return l[0] # 返回数字 # 返回内部函数 return add_one上面的代码中,我们使用了一个列表l[0]来记录累加数,在内部函数add_one中对l[0]进行累加。
我们这样使用这个计数器:
c = counter()print(c()) # 1print(c()) # 2print(c()) # 3我们还可以使这个计数器能够设置累加的初始值,就是为counter 函数设置一个参数,如下:
def counter(start): l = [start] def add_one(): l[0] += 1 return l[0] return add_one这样我们即可以使用counter 来生成不同的累加器(从不同的初始值开始累加)。我们这样使用该计数器:
c1 = counter(1) # c1 从 1 开始累加print(c1()) # 2print(c1()) # 3print(c1()) # 4c5 = counter(5) # c5 从 5 开始累加print(c5()) # 6print(c5()) # 7print(c5()) # 8c1 从 1 开始累加,c5 从 5 开始累加,两个互不干扰。
3,什么是装饰器
装饰器是闭包的一种进阶应用。装饰器从字面上了解就是用来装饰,包装的。装饰器一般用来在不修改函数内部代码的情况下,为一个函数增加额外的新功能。
装饰器尽管功能强大,但也不是万能的,它也有自己适用场景:
- 缓存
- 身份认证
- 记录函数运行时间
- 输入的正当性判断
比方,我们有一个函数,如下:
def hello(): print('hello world.')假如我们想计算这个函数的运行时间,最直接的想法就是修改该函数,如下:
import timedef hello(): s = time.time() print('hello world.') e = time.time() print('fun:%s time used:%s' % (hello.__name__. e - s))# 调用函数hello()其中,time 模块是Python 中的内置模块,用于时间相关计算。
每个函数都有一个__name__ 属性,其值为函数的名字。不论我们是直接查看一个函数的__name__ 属性,还是将一个函数赋值给一个变量后,再查看这个变量的__name__ 属性,它们的值都是一样的(都是原来函数的名字):
print(hello.__name__) # hellof = hello # 调用 f() 和 hello() 的效果是一样的print(f.__name__) # hello但是,假如我们要为很多的函数增加这样的功能,要是都使用这种办法,那会相当的麻烦,这时候使用装饰器就非常的合适。
最简单的装饰器
装饰器应用的就是闭包的特性,所以编写装饰器的套路与闭包是一样的,就是有一个外部函数和一个内部函数,外部函数的返回值是内部函数。
我们先编写一个框架:
def timer(func): def wrapper(): pass return wrapper再来实现计时功能:
import timedef timer(func): def wrapper(): s = time.time() ret = func() e = time.time() print('fun:%s time used:%s' % (func.__name__, e - s)) return ret return wrapperdef hello(): print('hello world.')该装饰器的名字是timer,其接受一个函数类型的参数func,func 就是要修饰的函数。
func 的函数原型要与内部函数wrapper 的原型一致(这是固定的写法),即函数参数相同,函数返回值也相同。
英文
wrapper就是装饰的意思。
其实timer 就是一个高阶函数,其参数是一个函数类型,返回值也是一个函数。我们可以这样使用timer 装饰器:
hello = timer(hello)hello()以上代码中,hello 函数作为参数传递给了timer 装饰器,返回结果用hello 变量接收,最后调用hello()。这就是装饰器的本来用法。
只不过,Python 提供了一种语法糖,使得装饰器的使用方法更加简单优雅。如下:
@timerdef hello(): print('hello world.')hello()直接在原函数hello 的上方写一个语法糖@timer,其实这个作用就相当于hello = timer(hello)。
用类实现装饰器
在上面的代码中,是用函数(也就是timer 函数)来实现的装饰器,我们也可以用类来实现装饰器。
用类实现装饰器,主要依赖的是__init__ 方法和__call__ 方法。
我们知道,实现
__call__方法的类,其对象可以像函数一样被调用。
用类来实现timer 装饰器,如下:
import timeclass timer: def __init__(self, func): self.func = func def __call__(self): s = time.time() ret = self.func() e = time.time() print('fun:%s time used:%s' % (self.func.__name__, e - s)) return ret@timerdef hello(): print('hello world.')print(hello())其中,构造方法__init__接收一个函数类型的参数func,而后,__call__方法就相当于wrapper 函数。
用类实现的装饰器的使用方法,与用函数实现的装饰器的使用方法是一样的。
4,被修饰的函数带有参数
假如hello 函数带有参数,如下:
def hello(s): print('hello %s.' % s)那么装饰器应该像下面这样:
import timedef timer(func): def wrapper(args): s = time.time() ret = func(args) e = time.time() print('fun:%s time used:%s' % (func.__name__, e - s)) return ret return wrapper@timerdef hello(s): print('hello %s.' % s)hello('python')timer 函数的参数仍然是要被修饰的函数,wrapper 函数的原型与hello 函数保持一致。
用类来实现,如下:
import timeclass timer: def __init__(self, func): self.func = func def __call__(self, args): s = time.time() ret = self.func(args) e = time.time() print('fun:%s time used:%s' % (self.func.__name__, e - s)) return ret@timerdef hello(s): print('hello %s.' % s)print(hello('python'))不定长参数装饰器
假如hello 函数的参数是不定长的,timer 应该是如下这样:
import timedef timer(func): def wrapper(*args, **kw): s = time.time() ret = func(*args, **kw) e = time.time() print('fun:%s time used:%s' % (func.__name__, e - s)) return ret return wrapper@timerdef hello(s1, s2): # 带有两个参数 print('hello %s %s.' % (s1, s2))@timerdef hello_java(): # 没有参数 print('hello java.')hello('python2', 'python3')hello_java()这样的装饰器timer,可以修饰带有任意参数的函数。
用类来实现,如下:
import timeclass timer: def __init__(self, func): self.func = func def __call__(self, *args, **kw): s = time.time() ret = self.func(*args, **kw) e = time.time() print('fun:%s time used:%s' % (self.func.__name__, e - s)) return ret@timerdef hello(s1, s2): # 带有两个参数 print('hello %s %s.' % (s1, s2))@timerdef hello_java(): # 没有参数 print('hello java.')hello('python2', 'python3')hello_java()5,装饰器带有参数
假如装饰器也需要带有参数,那么则需要在原来的timer 函数的外层再嵌套一层函数Timer,Timer 也带有参数,如下:
import timedef Timer(flag): def timer(func): def wrapper(*args, **kw): s = time.time() ret = func(*args, **kw) e = time.time() print('flag:%s fun:%s time used:%s' % (flag, func.__name__, e - s)) return ret return wrapper return timer@Timer(1)def hello(s1, s2): # 带有两个参数 print('hello %s %s.' % (s1, s2))@Timer(2)def hello_java(): # 没有参数 print('hello java.')hello('python2', 'python3')hello_java()从上面的代码中可以看到,timer 的结构没有改变,只是在wrapper 的内部使用了flag 变量,而后timer 的外层多了一层Timer,Timer 的返回值是timer,我们最终使用的装饰器是Timer。
我们通过函数.__name__ 来查看函数的__name__ 值:
print(hello.__name__) # wrapperprint(hello_java.__name__) # wrapper可以发现hello 和 hello_java 的__name__ 值都是wrapper(即内部函数wrapper 的名字),而不是hello 和 hello_java,这并不符合我们的需要,由于我们的初衷只是想添加hello 与hello_java的功能,但并不想改变它们的函数名字。
6,使用 @functools.wraps
我们可以使用functools模块的wraps装饰器来修饰wrapper 函数,以处理这个问题,如下:
import timeimport functoolsdef Timer(flag): def timer(func): @functools.wraps(func) def wrapper(*args, **kw): s = time.time() ret = func(*args, **kw) e = time.time() print('flag:%s fun:%s time used:%s' % (flag, func.__name__, e - s)) return ret return wrapper return timer@Timer(1)def hello(s1, s2): # 带有两个参数 print('hello %s %s.' % (s1, s2))@Timer(2)def hello_java(): # 没有参数 print('hello java.')此时,再查看hello 与 hello_java 的 __name__值,分别是hello 和 hello_java。
7,装饰器可以叠加使用
装饰器也可以叠加使用,如下:
@decorator1@decorator2@decorator3def func(): ...上面代码的所用相当于:
decorator1(decorator2(decorator3(func)))8,一个较通用的装饰器模板
编写装饰器有肯定的套路,根据上文的详情,我们可以归纳出一个较通用的装饰器模板:
def func_name(func_args): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): # 在这里可以使用func_args,*args,**kw # 逻辑解决 ... ret = func(*args, **kw) # 逻辑解决 ... return ret return wrapper return decorator# 使用装饰器 func_name@func_name(func_args)def func_a(*args, **kw): pass在上面的模板中:
func_name是装饰器的名字,该装饰器可以接收参数func_args- 内部函数
decorator的参数func,是一个函数类型的参数,就是将来要修饰的函数 func的参数列表可以是任意的,由于我们使用的是*args, **kw- 内部函数
wrapper的原型(即参数与返回值)要与 被修饰的函数func保持统一 @functools.wraps的作用是保留被装饰的原函数的少量元信息(比方__name__属性)
与装饰器相关的模块有functools 和 wrapt,可以使用这两个模块来优化完善你写的装饰器,感兴趣的小伙伴可以自己拓展学习。
(完。)
推荐阅读:
Python 简明教程 —17,Python 模块与包
Python 简明教程 —18,Python 面向对象
Python 简明教程 —19,Python 类与对象
Python 简明教程 —20,Python 类中的属性与方法
Python 简明教程 —21,Python 继承与多态
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Python 简明教程 — 22,Python 闭包与装饰器