Python 装饰器
Posted 烟草的香味
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 装饰器相关的知识,希望对你有一定的参考价值。
首先


需求来了
有如下几个封装好的函数供调用:

现在需要在每个函数执行前进行日志记录:
第一个方案

修改每个函数,添加日志记录的代码
但这样显然不太好,存在大量的重复代码,可以将重复代码封装为一个方法
第二个方案

这样的确是比第一个方案好多了,但是不符合开闭原则,即现有的代码不要去修改,而在基础的功能上进行二次开发
第三个方案

这样的确很好,但是在调用的时候太麻烦了,而且函数名字也变了,以前写好的代码全部都要修改,想办法让函数名不变就好了
第四个方案

这样就又好点了,在增加功能而不修改代码的前提下,也保证了函数名不变
这就是装饰器的功能了,装饰器和上边的代码实现的功能相同,只不过用了语法糖
使用装饰器的方案

装饰器原理
上述代码在执行@verify时,进行了如下操作:
执行verify函数 ,并将 @verify 下面的函数作为verify函数的参数
即@verify 等价于 verify(f1) , 其内部执行代码如下:
f1 = verify(f1)
如此便为装饰器
小小装饰器

输出结果:

装饰器的常用功能
- 引入日志
- 函数执行时间统计
- 执行函数前预备处理
- 执行函数后清理功能
- 权限校验等场景
- 缓存
装饰器实例
1.无参数的函数

2.被装饰的函数有参数

3.被装饰的函数有不定长参数

4.装饰器中的return

执行结果

如果修改装饰器为 return func(),则运行结果:

所以,一般情况下为了让装饰器更通用,可以有return
5.装饰器带参数,在原有装饰器的基础上,设置外部变量

运行结果为:

可以理解为:
foo()==timefun_arg("itcast")(foo)()
以上是关于Python 装饰器的主要内容,如果未能解决你的问题,请参考以下文章