python装饰器简介及同时使用多个装饰器的方法
python装饰器简介及同时使用多个装饰器
装饰器功能:
在不改变原有函数的情况下,唯已有函数添加新功能,且不改变函数名,无需改变函数的调用
特别适用于当多个函数需要添加相同功能时
python装饰器常用于以下几点:
- 登录验证
- 记录日志
- 检验输入是否合理
- Flask中的路由
什么是装饰器呢?装饰器如何使用?
# 声明装饰器 # 使用装饰器的函数,会自动将函数名传入func变量中 def decorator(func): def wrapper(): # 在func()函数外添加打印时间戳 print(time.time()) # 调用func(),实际使用中,该func就是使用装饰器的函数 func() return wrapper # 使用装饰器 # 使用装饰器只需要在声明函数前加上 @装饰器函数名 即可 @decorator def test(): print("this function' name is test") # 使用装饰器 @decorator def hello(): print("this function' name is hello") test() hello() # 运行结果 1587031347.2450945 this function' name is test 1587031347.2450945 this function' name is hello
如果使用装饰器的函数需要传入参数,只需改变一下装饰器函数即可
对上面的函数稍微修改即可
def decorator(func): def wrapper(arg): print(time.time()) func(arg) return wrapper @decorator def hello(arg): print("hello , ",arg) hello('武汉加油!') # 输出结果 1587031838.325085 hello , 武汉加油! 因为多个函数可以同时使用一个装饰器函数,考虑到各个函数需要的参数个数不同,可以将装饰器函数的参数设置为可变参数 def decorator(func): def wrapper(*args,**kwargs): print(time.time()) func(*args,**kwargs) return wrapper @decorator def sum(x,y): print(f'{x}+{y}={x+y}') sum(3,4) # 运行结果 1587032122.5290427 3+4=7
python支持一个函数同时使用多个装饰器
同时使用多个装饰器时,需要调用的函数本身只会执行一次
但会依次执行所有装饰器中的语句
执行顺序为从上到下依次执行
def decorator1(func): def wrapper(*args, **kwargs): print("the decoretor is decoretor1 !") func(*args, **kwargs) return wrapper def decorator2(func): def wrapper(*args, **kwargs): print("the decoretor is decoretor2 !") func(*args, **kwargs) return wrapper @decorator1 @decorator2 def myfun(func_name): print('This is a function named :', func_name) myfun('myfun')
因为 @decorator1 写在上面,因此会先执行decorator1 中的代码块,后执行decorator2 中的代码块
到此这篇关于python装饰器简介及同时使用多个装饰器的文章就介绍到这了,更多相关python多个装饰器使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
python详解如何通过sshtunnel pymssql实现远程连接数据库
为了安全起见,很多公司服务器数据库的访问多半是要做限制的,由专门的DBA管理,而且都是做的集群,数据库只能内网访问,所以就有一个直接的问题是,往往多数时候,在别的机器上(比如自己本地),是不能访问数据库的,给日常开发调试造成了很大不便2021-10-10python中input()与raw_input()的区别分析
这篇文章主要介绍了python中input()与raw_input()的区别,需要的朋友可以参考下2016-02-02Python使用wxPython和PyMuPDF实现合并PDF文档
处理大量的PDF文档可能会变得复杂和耗时,但是,使用Python编程和一些强大的库,可以使这个任务变得简单而高效,下面我们就来看看Python如何使用wxPython和PyMuPDF合并PDF文档并自动复制到剪贴板吧2023-11-11
最新评论