一、装饰器理解:
def set_func(func):
def call_func():
print("验证1")
print("验证2")
print("验证3")
func()
return call_func
@set_func # 等价于f1 = set_func(f1)
def f1():
print('f1')
python解释器就会从上到下解释代码,步骤如下:
- def set_func(func): ==>将set_func函数加载到内存
- @set_func
@set_func内部会执行一下操作:
1.执行set_func函数 ,并将 @set_func下面的函数作为set_func函数的参数,即:@set_func等价于 set_func(f1) 所以,内部就会去执行:
def call_func():
print("验证1")
print("验证2")
print("验证3")
func() # func是参数,此时 func 等于 f1
return call_func# 返回的 call_func ,call_func 代表的是函数,非执行函数 ,其实就是将原来的 f1 函数塞进另外一个函数中
2.将执行完的set_func函数返回值 赋值 给@set_func下面的函数的函数名f1 即将set_func的返回值再重新赋值给 f1,即:
新f1 = def call_func():
print("验证1")
print("验证2")
print("验证3")
func()
return call_func
二、多个装饰器对同一个函数装饰
# 定义函数:完成包裹数据
def makeBold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
# 定义函数:完成包裹数据
def makeItalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makeBold
def test1():
return "hello world-1"
@makeItalic
def test2():
return "hello world-2"
@makeBold
@makeItalic
def test3():
return "hello world-3"
print(test1())
print(test2())
print(test3())
运行结果:
<b>hello world-1</b>
<i>hello world-2</i>
<b><i>hello world-3</i></b>
多个装饰器对同一个函数装饰,先装谁(谁在最上面),先执行谁。
三、对有参数有返回值的函数进行装饰
一、被装饰的函数有参数
from time import ctime, sleep
def timefun(func):
def wrapped_func(a, b):
print("%s called at %s" % (func.__name__, ctime()))
print(a, b)
func(a, b)
return wrapped_func
@timefun
def foo(a, b):
print(a+b)
foo(3,5)
sleep(2)
foo(2,4)
运行结果:
foo called at Thu Oct 24 09:49:28 2019
3 5
8
foo called at Thu Oct 24 09:49:30 2019
2 4
6
二、被装饰的函数有不定长参数
from time import ctime, sleep
def timefun(func):
def wrapped_func(*args, **kwargs):
print("%s called at %s"%(func.__name__, ctime()))
func(*args, **kwargs)
return wrapped_func
@timefun
def foo(a, b, c):
print(a+b+c)
foo(3,5,7)
sleep(2)
foo(2,4,9)
运行结果:
foo called at Thu Oct 24 09:52:11 2019
15
foo called at Thu Oct 24 09:52:13 2019
15
三、被装饰的函数有返回值
from time import ctime, sleep
def timefun(func):
def wrapped_func():
print("%s called at %s" % (func.__name__, ctime()))
func()
return wrapped_func
@timefun
def foo():
print("I am foo")
@timefun
def getInfo():
return '----hahah---'
foo()
sleep(2)
foo()
print(getInfo())
执行结果:
foo called at Fri Nov 4 21:55:35 2016
I am foo
foo called at Fri Nov 4 21:55:37 2016
I am foo
getInfo called at Fri Nov 4 21:55:37 2016
None
如果修改装饰器为return func()
,则运行结果:
foo called at Fri Nov 4 21:55:57 2016
I am foo
foo called at Fri Nov 4 21:55:59 2016
I am foo
getInfo called at Fri Nov 4 21:55:59 2016
----hahah---
总结:一般情况下为了让装饰器更通用,可以有return
四、装饰器带参数,在原有装饰器的基础上,设置外部变量
from time import ctime, sleep
def timefun_arg(pre="hello"):
def timefun(func):
def wrapped_func():
print("%s called at %s %s" % (func.__name__, ctime(), pre))
return func()
return wrapped_func
return timefun
# 下面的装饰过程
# 1. 调用timefun_arg("itcast")
# 2. 将步骤1得到的返回值,即timefun返回, 然后timefun(foo)
# 3. 将time_fun(foo)的结果返回,即wrapped_func
# 4. 让foo = wrapped_fun,即foo现在指向wrapped_func
@timefun_arg("itcast")
def foo():
print("I am foo")
@timefun_arg("python")
def too():
print("I am too")
foo()
sleep(2)
foo()
print("-" * 10)
too()
sleep(2)
too()
可以理解为
foo() = timefun_arg("itcast")(foo)()
运行结果:
foo called at Thu Oct 24 09:55:09 2019 itcast
I am foo
foo called at Thu Oct 24 09:55:11 2019 itcast
I am foo
----------
too called at Thu Oct 24 09:55:11 2019 python
I am too
too called at Thu Oct 24 09:55:13 2019 python
I am too
四、保留元信息的装饰器
可以通过func.__name__获取函数名、可以通过func.__doc__获取函数的文档信息。
但是,通过使用装饰器,函数fun_one的元信息都丢失了:
from time import ctime, sleep
def timefun(func):
def wrapped_func(*args, **kwargs):
print("%s called at %s"%(func.__name__, ctime()))
func(*args, **kwargs)
return wrapped_func
@timefun
def foo(a, b, c):
"""
foo dec
"""
print(a+b+c)
print(foo.__name__)
print(foo.__doc__)
# 输出
# wrapped_func
# None
可以通过使用Python自带模块functools中的wraps来保留函数的元信息:
from time import ctime, sleep
from functools import wraps #<<<<
def timefun(func):
@wraps(func) #<<<<这里加 wraps(func) 即可
def wrapped_func(*args, **kwargs):
print("%s called at %s"%(func.__name__, ctime()))
func(*args, **kwargs)
return wrapped_func
@timefun
def foo(a, b, c):
"""
foo dec
"""
print(a+b+c)
print(foo.__name__)
print(foo.__doc__)
# 输出
# foo
# foo dec
五、类装饰器
装饰器函数其实是这样一个接口约束,它必须接受一个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---