Python中装饰器学习总结


Posted in Python onFebruary 10, 2018

本文研究的主要内容是Python中装饰器相关学习总结,具体如下。

装饰器(decorator)功能

  • 引入日志
  • 函数执行时间统计
  • 执行函数前预备处理
  • 执行函数后清理功能
  • 权限校验等场景
  • 缓存

装饰器示例

例1:无参数的函数

from time import ctime, sleep

def timefun(func):
 def wrappedfunc():
  print("%s called at %s"%(func.__name__, ctime()))
  func()
 return wrappedfunc

@timefun
def foo():
 print("I am foo")

foo()
sleep(2)
foo()

分析如下:

上面代码理解装饰器执行行为可理解成

foo = timefun(foo)

1,foo先作为参数赋值给func后,foo接收指向timefun返回的wrappedfunc
2,调用foo(),即等价调用wrappedfunc()
3,内部函数wrappedfunc被引用,所以外部函数的func变量(自由变量)并没有释放
4,func里保存的是原foo函数对象

例2:被装饰的函数有参数

from time import ctime, sleep

def timefun(func):
 def wrappedfunc(a, b):
  print("%s called at %s"%(func.__name__, ctime()))
  print(a, b)
  func(a, b)
 return wrappedfunc

@timefun
def foo(a, b):
 print(a+b)

foo(3,5)
sleep(2)
foo(2,4)

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

from time import ctime, sleep

def timefun(func):
 def wrappedfunc(*args, **kwargs):
  print("%s called at %s"%(func.__name__, ctime()))
  func(*args, **kwargs)
 return wrappedfunc

@timefun
def foo(a, b, c):
 print(a+b+c)

foo(3,5,7)
sleep(2)
foo(2,4,9)

例4:装饰器中的return

from time import ctime, sleep

def timefun(func):
 def wrappedfunc():
  print("%s called at %s"%(func.__name__, ctime()))
  func()
 return wrappedfunc

@timefun
def foo():
 print("I am foo")

@timefun
def getInfo():
 return '----hahah---'

foo()
sleep(2)
foo()


print(getInfo())

执行结果:

foo called at Sun Jun 18 00:31:53 2017
I am foo
foo called at Sun Jun 18 00:31:55 2017
I am foo
getInfo called at Sun Jun 18 00:31:55 2017
None

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

foo called at Sun Jun 18 00:34:12 2017
I am foo
foo called at Sun Jun 18 00:34:14 2017
I am foo
getInfo called at Sun Jun 18 00:34:14 2017
----hahah---

小结:一般情况下为了让装饰器更通用,可以有return

例5:装饰器带参数,在原有装饰器的基础上,设置外部变量

from time import ctime, sleep

def timefun_arg(pre="hello"):
 def timefun(func):
  def wrappedfunc():
   print("%s called at %s %s"%(func.__name__, ctime(), pre))
   return func()
  return wrappedfunc
 return timefun

@timefun_arg("itcast")
def foo():
 print("I am foo")

@timefun_arg("python")
def too():
 print("I am too")

foo()
sleep(2)
foo()

too()
sleep(2)
too()
可以理解为

foo()==timefun_arg("itcast")(foo)()

例6:类装饰器

装饰器函数其实是这样一个接口约束,它必须接受一个callable对象作为参数,然后返回一个callable对象。在Python中一般callable对象都是函数,但也有例外。只要某个对象重写了 call() 方法,那么这个对象就是callable的。

class Test():
 def __call__(self):
  print('call me!')

t = Test()
t() # call me
类装饰器demo


class Test(object):
 def __init__(self, func):
  print("---初始化---")
  print("func name is %s"%func.__name__)
  self.__func = func
 def __call__(self):
  print("---装饰器中的功能---")
  self.__func()

说明:

1. 当用Test来装作装饰器对test函数进行装饰的时候,首先会创建Test的实例对象,并且会把test这个函数名当做参数传递到init方法中
即在init方法中的func变量指向了test函数体
2. test函数相当于指向了用Test创建出来的实例对象
3. 当在使用test()进行调用时,就相当于让这个对象(),因此会调用这个对象的call方法
4. 为了能够在call方法中调用原来test指向的函数体,所以在init方法中就需要一个实例属性来保存这个函数体的引用
所以才有了self.func = func这句代码,从而在调用__call方法中能够调用到test之前的函数体

@Test 
def test(): 
print(“—-test—”) 
test() 
showpy()#如果把这句话注释,重新运行程序,依然会看到”?初始化?”

运行结果如下:

---初始化---
func name is test
---装饰器中的功能---
----test---

wraps函数

使用装饰器时,有一些细节需要被注意。例如,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变)。

添加后由于函数名和函数的doc发生了改变,对测试结果有一些影响,例如:

def note(func):
 "note function"
 def wrapper():
  "wrapper function"
  print('note something')
  return func()
 return wrapper

@note
def test():
 "test function"
 print('I am test')

test()
print(test.__doc__)

运行结果

note something
I am test
wrapper function

所以,Python的functools包中提供了一个叫wraps的装饰器来消除这样的副作用。例如:

import functools
def note(func):
 "note function"
 @functools.wraps(func)
 def wrapper():
  "wrapper function"
  print('note something')
  return func()
 return wrapper

@note
def test():
 "test function"
 print('I am test')

test()
print(test.__doc__)

运行结果

note something
I am test
test function

总结

以上就是本文关于Python中装饰器学习总结的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
Django 实现下载文件功能的示例
Mar 06 Python
详解Python中如何写控制台进度条的整理
Mar 07 Python
Python3安装Pillow与PIL的方法
Apr 03 Python
python实现植物大战僵尸游戏实例代码
Jun 10 Python
python中类的输出或类的实例输出为这种形式的原因
Aug 12 Python
Python pandas实现excel工作表合并功能详解
Aug 29 Python
Python提取PDF内容的方法(文本、图像、线条等)
Sep 25 Python
解决pycharm最左侧Tool Buttons显示不全的问题
Dec 17 Python
pandas实现DataFrame显示最大行列,不省略显示实例
Dec 26 Python
解决pycharm安装第三方库失败的问题
May 09 Python
keras中的卷积层&池化层的用法
May 22 Python
Python生成并下载文件后端代码实例
Aug 31 Python
Python基于hashlib模块的文件MD5一致性加密验证示例
Feb 10 #Python
Python中生成器和迭代器的区别详解
Feb 10 #Python
详解python中的线程
Feb 10 #Python
Odoo中如何生成唯一不重复的序列号详解
Feb 10 #Python
python TCP Socket的粘包和分包的处理详解
Feb 09 #Python
python实现Adapter模式实例代码
Feb 09 #Python
python实现Decorator模式实例代码
Feb 09 #Python
You might like
PHP下对字符串的递增运算代码
2010/08/21 PHP
php中的Base62类(适用于数值转字符串)
2013/08/12 PHP
smarty实现多级分类的方法
2014/12/05 PHP
php实现网页缓存的工具类分享
2015/07/14 PHP
php rsa 加密,解密,签名,验签详解
2016/12/06 PHP
浅谈PHP命令执行php文件需要注意的问题
2016/12/16 PHP
一个JavaScript继承的实现
2006/10/24 Javascript
JavaScript基础语法、dom操作树及document对象
2014/12/02 Javascript
JavaScript错误处理
2015/02/03 Javascript
javascript实现仿百度图片的瀑布流加载效果
2016/04/20 Javascript
js将滚动条滚动到指定位置的简单实现方法
2016/06/25 Javascript
Js获取当前日期时间及格式化代码
2016/09/17 Javascript
微信小程序 在Chrome浏览器上运行以及WebStorm的使用
2016/09/27 Javascript
AngularJs点击状态值改变背景色的实例
2017/12/18 Javascript
微信小程序实现banner图轮播效果
2020/06/28 Javascript
详解nvm管理多版本node踩坑
2019/07/26 Javascript
详解webpack引用jquery(第三方模块)的三种办法
2019/08/21 jQuery
Node.js API详解之 module模块用法实例分析
2020/05/13 Javascript
JS画布动态实现黑客帝国背景效果
2020/11/08 Javascript
Python cookbook(数据结构与算法)筛选及提取序列中元素的方法
2018/03/19 Python
Django rest framework实现分页的示例
2018/05/24 Python
Python采集猫眼两万条数据 对《无名之辈》影评进行分析
2018/12/05 Python
Python pyautogui模块实现鼠标键盘自动化方法详解
2020/02/17 Python
windows下Pycharm安装opencv的多种方法
2020/03/05 Python
python 使用while循环输出*组成的菱形实例
2020/04/12 Python
django的403/404/500错误自定义页面的配置方式
2020/05/21 Python
结合CSS3的新特性来总结垂直居中的实现方法
2016/05/30 HTML / CSS
NBA欧洲商店(法国):NBA Europe Store FR
2016/10/19 全球购物
美国滑雪和滑雪板商店:Buckman
2018/03/03 全球购物
T3官网:头发造型工具
2019/12/26 全球购物
程序员岗位职责
2013/11/11 职场文书
低碳环保演讲稿
2014/08/28 职场文书
未婚证明书模板
2014/10/08 职场文书
杭州黄龙洞导游词
2015/02/10 职场文书
2015年社区关工委工作总结
2015/04/03 职场文书
2015暑假社会调查报告
2015/07/13 职场文书