python装饰器原理与用法深入详解


Posted in Python onDecember 19, 2019

本文实例讲述了python装饰器原理与用法。分享给大家供大家参考,具体如下:

你会Python嘛?
我会!
那你给我讲下Python装饰器吧!
Python装饰器啊?我没用过哎

以上是我一个哥们面试时候发生的真实对白。

----------------------------------------------分割线------------------------------------------------------------------------------

简言之,python装饰器就是用于拓展原来函数功能的一种函数,这个函数的特殊之处在于它的返回值也是一个函数,使用python装饰器的好处就是在不用更改原函数的代码前提下给函数增加新的功能。
一般而言,我们要想拓展原来函数代码,最直接的办法就是侵入代码里面修改,例如:

import time
def func():
  print("hello")
  time.sleep(1)
  print("world")

这是我们最原始的的一个函数,然后我们试图记录下这个函数执行的总时间,那最简单的做法就是:

#原始侵入,篡改原函数
import time
def func():
  startTime = time.time()
  print("hello")
  time.sleep(1)
  print("world")
  endTime = time.time()
  msecs = (endTime - startTime)*1000
  print("time is %d ms" %msecs)

但是如果你的Boss在公司里面和你说:“小祁,这段代码是我们公司的核心代码,你不能直接去改我们的核心代码。”那该怎么办呢,我们仿照装饰器先自己试着写一下:

#避免直接侵入原函数修改,但是生效需要再次执行函数
import time
def deco(func):
  startTime = time.time()
  func()
  endTime = time.time()
  msecs = (endTime - startTime)*1000
  print("time is %d ms" %msecs)
def func():
  print("hello")
  time.sleep(1)
  print("world")
if __name__ == '__main__':
  f = func
  deco(f)#只有把func()或者f()作为参数执行,新加入功能才会生效
  print("f.__name__ is",f.__name__)#f的name就是func

这里我们定义了一个函数deco,它的参数是一个函数,然后给这个函数嵌入了计时功能。然后你可以拍着胸脯对老板说,看吧,不用动你原来的代码,我照样拓展了它的函数功能。

然后你的老板有对你说:“小祁,我们公司核心代码区域有一千万个func()函数,从func01()到func1kw(),按你的方案,想要拓展这一千万个函数功能,就是要执行一千万次deco()函数,这可不行呀,我心疼我的机器。”

好了,你终于受够你老板了,准备辞职了,然后你无意间听到了装饰器这个神器,突然发现能满足你闫博士的要求了。

我们先实现一个最简陋的装饰器,不使用任何语法糖和高级语法,看看装饰器最原始的面貌:

#既不需要侵入,也不需要函数重复执行
import time
def deco(func):
  def wrapper():
    startTime = time.time()
    func()
    endTime = time.time()
    msecs = (endTime - startTime)*1000
    print("time is %d ms" %msecs)
  return wrapper
@deco
def func():
  print("hello")
  time.sleep(1)
  print("world")
if __name__ == '__main__':
  f = func #这里f被赋值为func,执行f()就是执行func()
  f()

这里的deco函数就是最原始的装饰器,它的参数是一个函数,然后返回值也是一个函数。其中作为参数的这个函数func()就在返回函数wrapper()的内部执行。然后在函数func()前面加上@deco,func()函数就相当于被注入了计时功能,现在只要调用func(),它就已经变身为“新的功能更多”的函数了。

所以这里装饰器就像一个注入符号:有了它,拓展了原来函数的功能既不需要侵入函数内更改代码,也不需要重复执行原函数。

#带有参数的装饰器
import time
def deco(func):
  def wrapper(a,b):
    startTime = time.time()
    func(a,b)
    endTime = time.time()
    msecs = (endTime - startTime)*1000
    print("time is %d ms" %msecs)
  return wrapper
@deco
def func(a,b):
  print("hello,here is a func for add :")
  time.sleep(1)
  print("result is %d" %(a+b))
if __name__ == '__main__':
  f = func
  f(3,4)
  #func()

然后你满足了Boss的要求后,Boss又说:“小祁,我让你拓展的函数好多可是有参数的呀,有的参数还是个数不定的那种,你的装饰器搞的定不?”然后你嘿嘿一笑,深藏功与名!

#带有不定参数的装饰器
import time
def deco(func):
  def wrapper(*args, **kwargs):
    startTime = time.time()
    func(*args, **kwargs)
    endTime = time.time()
    msecs = (endTime - startTime)*1000
    print("time is %d ms" %msecs)
  return wrapper
@deco
def func(a,b):
  print("hello,here is a func for add :")
  time.sleep(1)
  print("result is %d" %(a+b))
@deco
def func2(a,b,c):
  print("hello,here is a func for add :")
  time.sleep(1)
  print("result is %d" %(a+b+c))
if __name__ == '__main__':
  f = func
  func2(3,4,5)
  f(3,4)
  #func()

最后,你的老板说:“可以的,小祁,我这里一个函数需要加入很多功能,一个装饰器怕是搞不定,装饰器能支持多个嘛"

最后你就把这段代码丢给了他:

#多个装饰器
import time
def deco01(func):
  def wrapper(*args, **kwargs):
    print("this is deco01")
    startTime = time.time()
    func(*args, **kwargs)
    endTime = time.time()
    msecs = (endTime - startTime)*1000
    print("time is %d ms" %msecs)
    print("deco01 end here")
  return wrapper
def deco02(func):
  def wrapper(*args, **kwargs):
    print("this is deco02")
    func(*args, **kwargs)
    print("deco02 end here")
  return wrapper
@deco01
@deco02
def func(a,b):
  print("hello,here is a func for add :")
  time.sleep(1)
  print("result is %d" %(a+b))
if __name__ == '__main__':
  f = func
  f(3,4)
  #func()
'''
this is deco01
this is deco02
hello,here is a func for add :
result is 7
deco02 end here
time is 1003 ms
deco01 end here
'''

多个装饰器执行的顺序就是从最后一个装饰器开始,执行到第一个装饰器,再执行函数本身。

盗用评论里面一位童鞋的例子:

def dec1(func):
  print("1111")
  def one():
    print("2222")
    func()
    print("3333")
  return one
def dec2(func):
  print("aaaa")
  def two():
    print("bbbb")
    func()
    print("cccc")
  return two
@dec1
@dec2
def test():
  print("test test")
test()

输出:

aaaa
1111
2222
bbbb
test test
cccc
3333

装饰器的外函数和内函数之间的语句是没有装饰到目标函数上的,而是在装载装饰器时的附加操作。

17~20行是装载装饰器的过程,相当于执行了test=dect1(dect2(test)),此时先执行dect2(test),结果是输出aaaa、将func指向函数test、并返回函数two,然后执行dect1(two),结果是输出1111、将func指向函数two、并返回函数one,然后进行赋值。

用函数替代了函数名test。 22行则是实际调用被装载的函数,这时实际上执行的是函数one,运行到func()时执行函数two,再运行到func()时执行未修饰的函数test。

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python 不关闭控制台的实现方法
Oct 23 Python
关于你不想知道的所有Python3 unicode特性
Nov 28 Python
用Python计算三角函数之atan()方法的使用
May 15 Python
Python之多线程爬虫抓取网页图片的示例代码
Jan 10 Python
python计算两个数的百分比方法
Jun 29 Python
详解Python中的分组函数groupby和itertools)
Jul 11 Python
pyspark操作MongoDB的方法步骤
Jan 04 Python
对PyQt5基本窗口控件 QMainWindow的使用详解
Jun 19 Python
python3.x 生成3维随机数组实例
Nov 28 Python
keras获得某一层或者某层权重的输出实例
Jan 24 Python
Python之Matplotlib文字与注释的使用方法
Jun 18 Python
使用pytorch实现线性回归
Apr 11 Python
python列表生成器迭代器实例解析
Dec 19 #Python
Python tensorflow实现mnist手写数字识别示例【非卷积与卷积实现】
Dec 19 #Python
Python: 传递列表副本方式
Dec 19 #Python
python内置模块collections知识点总结
Dec 19 #Python
Python操作redis和mongoDB的方法
Dec 19 #Python
Python 实现Serial 与STM32J进行串口通讯
Dec 18 #Python
实现Python与STM32通信方式
Dec 18 #Python
You might like
php空间不支持socket但支持curl时recaptcha的用法
2011/11/07 PHP
php实现cc攻击防御和防止快速刷新页面示例
2014/02/13 PHP
yii框架builder、update、delete使用方法
2014/04/30 PHP
关于laravel 日志写入失败问题汇总
2019/10/17 PHP
js或者jquery判断图片是否加载完成实现代码
2013/03/20 Javascript
单击某一段文字改写文本颜色
2014/06/06 Javascript
基于Node.js的WebSocket通信实现
2017/03/11 Javascript
jQuery查找和过滤_动力节点节点Java学院整理
2017/07/04 jQuery
微信小程序 自定义消息提示框
2017/08/06 Javascript
Vue.js组件高级特性实例详解
2018/12/24 Javascript
生产制造追溯系统之再说条码打印
2019/06/03 Javascript
js实现拾色器插件(ColorPicker)
2020/05/21 Javascript
vue style width a href动态拼接问题的解决
2020/08/07 Javascript
[06:45]DOTA2-DPC中国联赛 正赛 Magma vs LBZS 选手采访
2021/03/11 DOTA
python中lambda函数 list comprehension 和 zip函数使用指南
2014/09/28 Python
使用Python对Excel进行读写操作
2017/03/30 Python
Python入门_浅谈数据结构的4种基本类型
2017/05/16 Python
python使用super()出现错误解决办法
2017/08/14 Python
关于Django显示时间你应该知道的一些问题
2017/12/25 Python
基于tensorflow加载部分层的方法
2018/07/26 Python
python 从文件夹抽取图片另存的方法
2018/12/04 Python
pytorch 转换矩阵的维数位置方法
2018/12/08 Python
使用Python3+PyQT5+Pyserial 实现简单的串口工具方法
2019/02/13 Python
Python3中_(下划线)和__(双下划线)的用途和区别
2019/04/26 Python
使用python画社交网络图实例代码
2019/07/10 Python
利用Python的turtle库绘制玫瑰教程
2019/11/23 Python
解决运行django程序出错问题 'str'object has no attribute'_meta'
2020/07/15 Python
用python对excel进行操作(读,写,修改)
2020/12/25 Python
英国运动风奢侈品购物网站:Maison De Fashion
2020/08/28 全球购物
Prototype如何更新局部页面
2013/03/03 面试题
学术会议欢迎词
2014/01/09 职场文书
党员专题组织生活会发言材料
2014/10/17 职场文书
出国导师推荐信
2015/03/25 职场文书
python Polars库的使用简介
2021/04/21 Python
Python实现排序方法常见的四种
2021/07/15 Python
我家女友可不止可爱呢 公开OP主题曲无字幕动画MV
2022/04/11 日漫