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函数装饰器详解的更多相关文章

  1. python装饰器1:函数装饰器详解

    装饰器1:函数装饰器 装饰器2:类装饰器 装饰器3:进阶 先混个眼熟 谁可以作为装饰器(可以将谁编写成装饰器): 函数 方法 实现了__call__的可调用类 装饰器可以去装饰谁(谁可以被装饰): 函 ...

  2. python之装饰器详解

    这几天翻看python语法,看到装饰器这里着实卡了一阵,最初认为也就是个函数指针的用法,但仔细研究后发现,不止这么简单. 首先很多资料将装饰器定义为AOP的范畴,也就是Aspect Oriented ...

  3. python 叠加装饰器详解

    def out1(func1): #7.func1=in2的内存地址,就是in2 print('out1') def in1(): #8.调用函数index() 因为函数在in1里,所以首先运行in1 ...

  4. 【python】装饰器详解推荐

    复杂道理浅中来,见过的解释最清楚的一篇文章: https://blog.csdn.net/xiangxianghehe/article/details/77170585

  5. Python函数装饰器原理与用法详解《摘》

    本文实例讲述了Python函数装饰器原理与用法.分享给大家供大家参考,具体如下: 装饰器本质上是一个函数,该函数用来处理其他函数,它可以让其他函数在不需要修改代码的前提下增加额外的功能,装饰器的返回值 ...

  6. python设计模式之装饰器详解(三)

    python的装饰器使用是python语言一个非常重要的部分,装饰器是程序设计模式中装饰模式的具体化,python提供了特殊的语法糖可以非常方便的实现装饰模式. 系列文章 python设计模式之单例模 ...

  7. python函数-装饰器

    python函数-装饰器 1.装饰器的原则--开放封闭原则 开放:对于添加新功能是开放的 封闭:对于修改原功能是封闭的 2.装饰器的作用 在不更改原函数调用方式的前提下对原函数添加新功能 3.装饰器的 ...

  8. Python函数装饰器高级用法

    在了解了Python函数装饰器基础知识和闭包之后,开始正式学习函数装饰器. 典型的函数装饰器 以下示例定义了一个装饰器,输出函数的运行时间: 函数装饰器和闭包紧密结合,入参func代表被装饰函数,通过 ...

  9. Python 函数装饰器

    首次接触到装饰器的概念,太菜啦! Python 装饰器可以大大节省代码的编写量,提升代码的重复使用率.函数装饰器其本质也是一个函数,我们可以把它理解为函数中定义了一个子函数. 例如我们有这么一个需求, ...

随机推荐

  1. oracle更新数据库密码

    今天忘记了system的密码,记录一下. sqlpls  /  as sysdba alter  user  system  identified by "GYSUhbyqwgu" ...

  2. python类中方法__str__()和__repr__()简单粗暴总结

    在交互式模式下,类中同时实现__str__()和__repr__()方法: 直接输入实例名称显示repr返回的类容: 用print打印实例名称显示str返回的内容: >>> clas ...

  3. lik模糊e查询语句,索引使用效果详解

    一.like查询与索引 在oracle里的一个超级大的表中,我们的where条件的列有建索引的话,会走索引唯一扫描INDEX UNIQUE SCAN.如select * from table wher ...

  4. Hibernate 一对多配置 级联操作(级联失败问题分析解决)

    一方: package com.xdfstar.domain; import java.io.Serializable;import java.util.Date;import java.util.H ...

  5. BZOJ3227 [sdoi2008]红黑树

    贪心什么的太神仙了( 老老实实dp于是就是沙茶题了 f[i][d][0/1]表示i个节点bh为d当前节点颜色白/黑[好好读题是真.. 转移一下然后就可以打表了( 由于我们发现这玩意很好卡有很好的性质( ...

  6. MySQL-触发案列

    1.更新案例 DELIMITER $$ USE `haochacang`$$ DROP TRIGGER /*!50032 IF EXISTS */ `customer_info_update`$$ C ...

  7. cookie和session的区别有哪些

    前言: cookie和session有着千丝万缕的联系,本文将详细介绍2者的区别. 1.存储位置不同 cookie的数据信息存放在客户端浏览器上. session的数据信息存放在服务器上. 2.存储容 ...

  8. 【NLP新闻-2013.06.03】New Book Where Humans Meet Machines

    英语原文地址:http://nlp.hivefire.com/articles/share/39865/ 注:本人翻译NLP新闻只为学习专业英语和扩展视野,如果翻译的不好,请谅解! (我挺想看这本书的 ...

  9. SpringMvc返回JSON的工作原理。

    一:导入jar包.然后在springmvc.xml中配置上这么一句话 <!-- 能支持springmvc更高级的一些功能,JSR303校验,快捷的ajax,处理JSON数据.映射动态请求 --& ...

  10. 10.14.1-linux设置时间等

    设置时间[root@wen /]# date -s "20171014 15:42:00"2017年 10月 14日 星期六 15:42:00 CST 格式化时间[root@wen ...