侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python中装饰器学习总结

Python  /  管理员 发布于 7年前   216

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

装饰器(decorator)功能

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

装饰器示例

例1:无参数的函数

from time import ctime, sleepdef timefun(func): def wrappedfunc():  print("%s called at %s"%(func.__name__, ctime()))  func() return wrappedfunc@timefundef 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, sleepdef timefun(func): def wrappedfunc(a, b):  print("%s called at %s"%(func.__name__, ctime()))  print(a, b)  func(a, b) return wrappedfunc@timefundef foo(a, b): print(a+b)foo(3,5)sleep(2)foo(2,4)

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

from time import ctime, sleepdef timefun(func): def wrappedfunc(*args, **kwargs):  print("%s called at %s"%(func.__name__, ctime()))  func(*args, **kwargs) return wrappedfunc@timefundef foo(a, b, c): print(a+b+c)foo(3,5,7)sleep(2)foo(2,4,9)

例4:装饰器中的return

from time import ctime, sleepdef timefun(func): def wrappedfunc():  print("%s called at %s"%(func.__name__, ctime()))  func() return wrappedfunc@timefundef foo(): print("I am foo")@timefundef 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, sleepdef 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类装饰器democlass 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()#如果把这句话注释,重新运行程序,依然会看到”C初始化C”

运行结果如下:

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

wraps函数

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

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

def note(func): "note function" def wrapper():  "wrapper function"  print('note something')  return func() return wrapper@notedef test(): "test function" print('I am test')test()print(test.__doc__)

运行结果

note something
I am test
wrapper function

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

import functoolsdef note(func): "note function" @functools.wraps(func) def wrapper():  "wrapper function"  print('note something')  return func() return wrapper@notedef test(): "test function" print('I am test')test()print(test.__doc__)

运行结果

note something
I am test
test function

总结

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


  • 上一条:
    Python迭代器和生成器定义与用法示例
    下一条:
    Python基于hashlib模块的文件MD5一致性加密验证示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客