python函数装饰器详解
python装饰器(fuctional decorators)简单来说就是修改其他函数的函数。
这样的函数需要满足两个个条件:
1、不能修改原函数的源代码
2、不能改变原函数的调用方式
需要达到的效果:增加函数的功能
假设,我们已经定义了一个函数
import time
def test():
time.sleep(2)
print('The is test')
现在需要为这个程序添加一个功能:显示该程序运行的时间
一、预备知识
理解装饰器的难点在于:
1、理解python一切皆为对象的含义
2、高阶函数
3、嵌套函数
1、一切皆对象
这里只是简单看一下,理解函数即变量即可。后面学习深入会有更深入的理解。
>>> def say(name):
... return 'hello '+ name
...
>>> print(say())
>>> print(say('Michael'))
hello Michael
>>>
# 我们可以将函数名作为变量赋值给另一个变量,换句话说变量可以指向函数
>>> greet=say
>>> print(greet())
>>> print(greet('Bob'))
hello Bob
# 变量删除,对象也就不存在了
>>> del say
>>> say('Jack')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'say' is not defined
>>>
2、高阶函数
高阶函数有两类:
a.把一个函数名当作实参传给另外一个函数
b.返回值中包含函数名
python一切皆为对象,实际上函数名就是函数的地址,也可以认为,是函数的一个标签。这样就可以把函数名作为一个参数传给另一个函数,在另一个函数里做一些操作,就可以在不修改源代码的基础上,为函数增加一些功能。
import time
def test():
print('This is test') def deco(func):
start_t = time.time()
func()
end_t = time.time()
print('the func %s run time is %s' % (func, end_t-start_t)) deco(test)
在第11行处,把test作为实参传给形参func,在第7行处就是对形参的调用。func传入的是函数的地址,func()就是执行这个函数,这段代码运行的结果就是:
This is test
the func <function test at 0x00000195C816EAE8> run time is 0.0
那么再思考,如果不修改调用方式,就是一定要有test()这条语句,那么就用到了第二种高阶函数,即返回值中包含函数名
def test():
time.sleep(3)
print('This is test') def deco(func):
print('This is deco')
return func test = deco(test)
test()
这种方式虽然可以不改变调用方式,但是无法完成计时功能,运算结果
This is deco
This is test
3、嵌套函数
import time
def timer(func):
def deco():
start = time.time()
func()
stop = time.time()
print('The func running time is %s' % (stop - start))
return deco def test():
time.sleep(2)
print("This is test") test = timer(test)
test()
在第14行处,把test作为参数传递给了timer(),此时,在timer()内部,func = test,接下来,定义了一个deco()函数,当并未调用,只是在内存中保存了,并且标签为deco。在timer()函数的最后返回deco()的地址deco。
然后再把deco赋值给了test,那么此时test已经不是原来的test了,也就是test原来的那些函数体的标签换掉了,换成了deco。那么在第15行处调用的实际上是deco()。执行结果
This is test
The func running time is 2.000332832336426
那么通俗一点的理解就是:
把函数看成是盒子,test是小盒子,deco是中盒子,timer是大盒子。程序中,把小盒子test传递到大盒子temer中的中盒子deco,然后再把中盒子deco拿出来
,打开看看(调用)。
二、真正的装饰器
根据以上分析,装饰器在装饰时,需要在每个函数前面加上:
test = timer(test)
显然有些麻烦,Python提供了一种语法糖,即:
@timer
这两句是等价的,只要在函数前加上这句,就可以实现装饰作用。
以上为无参形式。
import time def decorator(func):
def wapper():#若被装饰函数含参,传到wapper即可
start_t = time.time()
func()
stop_t = time.time()
print('the func running time is %s' % (stop_t-start_t))
return wapper @decorator #test1=decorator(test1) =wapper大盒子替换到中盒子
def test():#表面是小盒子,实际上是中盒子
time.sleep(3)
print('in the test1')
执行结果:
in the test1
the func running time is 3.0000483989715576
含参的装饰器
对于一个实际问题,往往是有参数的,如果要在#8处,给被修饰函数加上参数,显然这段程序会报错的。错误原因是test()在调用的时候缺少了一个位置参数的。而我们知道test = func = deco,因此test()=func()=deco() ,那么当test(parameter)有参数时,就必须给func()和deco()也加上参数,为了使程序更加有扩展性,因此在装饰器中的deco()和func(),加如了可变参数*agrs和 **kwargs。
improt time def timer(func)
def deco(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
stop = time.time()
print(stop-start)
return deco @timer
def test(parameter):
time.sleep(2)
print("test is running!")
test()
带返回值的装饰器
test()返回值返回到deco()的内部,而不是test()即deco()的返回值,那么就需要再返回func()的值,因此就是:
def timer(func)
def deco(*args, **kwargs):
start = time.time()
res = func(*args, **kwargs)#
stop = time.time()
print(stop-start)
return res#
return deco
一个较为完整的装饰器
improt time def timer(func)
def deco(*args, **kwargs): #含参的test()函数
start = time.time()
res = func(*args, **kwargs)
stop = time.time()
print(stop-start)
return res #函数带有返回值
return deco @timer
def test(parameter):
time.sleep(2)
print("test is running!")
return "Returned value"
test()
更复杂的装饰器
又增加了一个需求,一个装饰器,对不同的函数有不同的装饰。那么就需要知道对哪个函数采取哪种装饰。因此,就需要装饰器带一个参数来标记一下。例如:
@decorator(parameter = value)
比如两个函数
def task1():
time.sleep(2)
print("in the task1") def task2():
time.sleep(2)
print("in the task2") task1()
task2()
要对这两个函数分别统计运行时间,但是要求统计之后输出:
the task1/task2 run time is : 2.00……
于是就要构造一个装饰器timer,并且需要告诉装饰器哪个是task1,哪个是task2,也就是要这样:
@timer(parameter='task1') #
def task1():
time.sleep(2)
print("in the task1") @timer(parameter='task2') #
def task2():
time.sleep(2)
print("in the task2") task1()
task2()
那么方法有了,但是我们需要考虑如何把这个parameter参数传递到装饰器中,我们以往的装饰器,都是传递函数名字进去,而这次,多了一个参数,要怎么做呢?
于是,就想到再加一层函数来接受参数,根据嵌套函数的概念,要想执行内函数,就要先执行外函数,才能调用到内函数,那么就有:
def timer(parameter): #
print("in the auth :", parameter) def outer_deco(func): #
print("in the outer_wrapper:", parameter) def deco(*args, **kwargs): return deco return outer_deco
首先timer(parameter),接收参数parameter=’task1/2’,而@timer(parameter)也恰巧带了括号,那么就会执行这个函数, 那么就是相当于:
timer = timer(parameter)
task1 = timer(task1)
完整的实现
import time
def timer(parameter):
def outer_wrapper(func):
def wrapper(*args, **kwargs):
if parameter == 'task1':
start = time.time()
func(*args, **kwargs)
stop = time.time()
print("the task1 run time is :", stop - start)
elif parameter == 'task2':
start = time.time()
func(*args, **kwargs)
stop = time.time()
print("the task2 run time is :", stop - start) return wrapper return outer_wrapper
@timer(parameter='task1')#1 timer = timer(parameter)此时timer=out_wrapper 2 task1 = timer(task1)此时相当于task1=wrapper(task1)
def task1(): time.sleep(2) print("in the task1") @timer(parameter='task2')
def task2(): time.sleep(2)
执行结果
in the task1
the task1 run time is : 2.000471591949463
in the task2
the task2 run time is : 2.000399589538574
python函数装饰器详解的更多相关文章
- python装饰器1:函数装饰器详解
装饰器1:函数装饰器 装饰器2:类装饰器 装饰器3:进阶 先混个眼熟 谁可以作为装饰器(可以将谁编写成装饰器): 函数 方法 实现了__call__的可调用类 装饰器可以去装饰谁(谁可以被装饰): 函 ...
- python之装饰器详解
这几天翻看python语法,看到装饰器这里着实卡了一阵,最初认为也就是个函数指针的用法,但仔细研究后发现,不止这么简单. 首先很多资料将装饰器定义为AOP的范畴,也就是Aspect Oriented ...
- python 叠加装饰器详解
def out1(func1): #7.func1=in2的内存地址,就是in2 print('out1') def in1(): #8.调用函数index() 因为函数在in1里,所以首先运行in1 ...
- 【python】装饰器详解推荐
复杂道理浅中来,见过的解释最清楚的一篇文章: https://blog.csdn.net/xiangxianghehe/article/details/77170585
- Python函数装饰器原理与用法详解《摘》
本文实例讲述了Python函数装饰器原理与用法.分享给大家供大家参考,具体如下: 装饰器本质上是一个函数,该函数用来处理其他函数,它可以让其他函数在不需要修改代码的前提下增加额外的功能,装饰器的返回值 ...
- python设计模式之装饰器详解(三)
python的装饰器使用是python语言一个非常重要的部分,装饰器是程序设计模式中装饰模式的具体化,python提供了特殊的语法糖可以非常方便的实现装饰模式. 系列文章 python设计模式之单例模 ...
- python函数-装饰器
python函数-装饰器 1.装饰器的原则--开放封闭原则 开放:对于添加新功能是开放的 封闭:对于修改原功能是封闭的 2.装饰器的作用 在不更改原函数调用方式的前提下对原函数添加新功能 3.装饰器的 ...
- Python函数装饰器高级用法
在了解了Python函数装饰器基础知识和闭包之后,开始正式学习函数装饰器. 典型的函数装饰器 以下示例定义了一个装饰器,输出函数的运行时间: 函数装饰器和闭包紧密结合,入参func代表被装饰函数,通过 ...
- Python 函数装饰器
首次接触到装饰器的概念,太菜啦! Python 装饰器可以大大节省代码的编写量,提升代码的重复使用率.函数装饰器其本质也是一个函数,我们可以把它理解为函数中定义了一个子函数. 例如我们有这么一个需求, ...
随机推荐
- 自己实现一个类似 jQuery 的函数库
假如我们有一个需求,需要给元素添加样式类,使用原生的JS很容易搞定. 1 抽取函数 function addClass(node, className){ node.classList.add(cla ...
- 二进制部署k8s
一.二进制部署 k8s集群 1)参考文章 博客: https://blog.qikqiak.com 文章: https://www.qikqiak.com/post/manual-install-hi ...
- Activiti6.0 java项目框架 spring5 SSM 工作流引擎 审批流程
工作流模块----------------------------------------------------------------------------------------------- ...
- jar 启动脚本
前段时间用springboot做项目后,每次重新发布都好麻烦, 所以写了个脚本来配合jenkins 发布: #!/bin/bash APP_NAME=application.jar function ...
- 基于TensorFlow Object Detection API进行迁移学习训练自己的人脸检测模型(二)
前言 已完成数据预处理工作,具体参照: 基于TensorFlow Object Detection API进行迁移学习训练自己的人脸检测模型(一) 设置配置文件 新建目录face_faster_rcn ...
- 基于英伟达Jetson TX1的GPU处理平台
基于英伟达Jetson TX1 GPU的HDMI图像输入的深度学习套件 [309] 本平台基于英伟达的Jetson TX1视觉计算的全功能开发板,配合本公司研发的HDMI输入图像采集板:Jetson ...
- Django中的APP
3. Django中的APP: 什么是APP?以及为什么要用APP? project --> 项目 (老男孩教育大学校) APP --> 应用 (Linux学院/Python学院/大数据学 ...
- IDS4授权分析
一.授权过程的场景名词 RO (resource owner): 资源所有者:用户. Resource Owner:简单理解为资源拥有者,文中称“user”: RS (resource server) ...
- SCM
scm即软件配置管理. 软件配置管理(SCM)是指通过执行版本控制.变更控制的规程,以及使用合适的配置管理软件,来保证所有配置项的完整性和可跟踪性,配置管理是对工作成果的一种有效保护. SCM(Sof ...
- 树的计数 Prüfer编码与Cayley公式 学习笔记
最近学习了Prüfer编码与Cayley公式,这两个强力的工具一般用于解决树的计数问题.现在博主只能学到浅层的内容,只会用不会证明. 推荐博客:https://blog.csdn.net/moreja ...