文章目录
1 装饰器的定义
1.把一个函数当作参数,返回一个替代版的函数,本质上就是一个返回函数的函数
2.可以在不改变原函数的基础上,给函数增加功能。
示例:增加原函数的功能
def decorate(fun):
def wrapper(*args,**kwargs):
print('Welcome to 2020')
fun()
return wrapper
@decorate
def fun():
print('Hello python!')
fun()
注意:decorate是用于返回wrapper(不带()表示返回函数,带()表示返回运行结果)
2 装饰器的调用方式
示例:计算函数f1的运行时间
import time
def decorator(fun):
def wrapper():
print(time.time())
fun()
return wrapper
def f1():
print('This is a function')
f = decorator(f1)##调用函数
f()
import time
def decorator(fun):
def wrapper():
print(time.time())
fun()
return wrapper
@decorator ###调用装饰器(写在原函数前面)
def f1():
print('This is a function')
f1()
3 处理的原函数中有参数
注意:会先运行装饰器,再运行原函数
示例:计算函数f1的运行时间
def decorator(func):
def wrapper(*args):
print(time.time())
func(*args)
return wrapper
@decorator
def f1(ser_name):
print('This is a service: ' + ser_name)
f1('http')
装饰器中也可以接受多个参数
示例:计算函数f2的运行时间
import time
def decorator(func):
def wrapper(*args):
print(time.time())
func(*args)
return wrapper
@decorator
def f2(ser_name1,ser_name2):
print('This is a service: ' + ser_name1)
print('This is a service: ' + ser_name2)
f2('http','ftp')
4 处理的原函数中有关键字参数
示例:计算函数f3的运行时间
import time
def decorator(func):
def wrapper(*args,**kwargs):
print(time.time())
func(*args,**kwargs)
return wrapper
@decorator
def f3(ser_name1,ser_name2,**kwargs):
print('This is a service: ' + ser_name1)
print('This is a service: ' + ser_name2)
print(kwargs)
f3('samba','nfs',a=1,b=[1,2,3],c='test')
5 处理的原函数中有返回值
注意:处理的原函数中有返回值时,需要在装饰器中对函数的运行结果处理(用一个变量保存函数 ,返回返回值)
示例:装饰器实现函数计时器
def fun_list(n):
return [2 * i for i in range(n)]
def fun_map(n):
return list(map(lambda x:x*2,range(n)))
import time
def timetest(fun):
def wrapper(*args,**kwargs):
start_time = time.time()
res = fun(*args,**kwargs)
end_time = time.time()
print('Running time is %.6f' %(end_time - start_time))
return res
return wrapper
@timetest
def fun_list(n):
return [2 * i for i in range(n)]
@timetest
def fun_map(n):
return list(map(lambda x:x*2,range(n)))
print(fun_list(10000))
print(fun_map(10000))
6.保留被装饰函数的函数名和信息文档
import time
import functools
def timetest(fun):
"""This is a decorator fun"""
@functools.wraps(fun)
def wrapper(*args,**kwargs):
"""This is a wrapper function"""
start_time = time.time()
res = fun(*args,**kwargs)
end_time = time.time()
print('Running time is: %.6f' %(end_time - start_time))
return res
return wrapper
@timetest
def fun_list(n):
"""This is the fun_list function"""
return [2 * i for i in range(n)]
@timetest
def fun_map(n):
"""This is the fun_map function"""
return list(map(lambda x:x*2,range(n)))
print(fun_list.__doc__)
print(fun_list.__name__)
7.带参数的装饰器
可以在装饰器外面再次封装,接收装饰器的参数
编写装饰器required_types, 条件如下:
1). 当装饰器为@required_types(int,float)确保函数接收到的每一>个参数都是int或者float类型;
2). 当装饰器为@required_types(list)确保函数接收到的每一个参数
都是list类型;
3). 当装饰器为@required_types(str,int)确保函数接收到的每一个>参数都是str或者int类型;
4). 如果参数不满足条件, 打印 TypeError:参数必须为xxxx类型
```python
import functools
def required_types(*kind):
def required(fun):
@functools.wraps(fun)
def wrapper(*args,**kwargs):
for i in args:
if not isinstance(i,kind):
print('TypeError:参数必须为%s,%s类型' %kind)
exit()
else:
res = fun(*args,**kwargs)
return res
return wrapper
return required
@required_types(float,float)
def add(a,b):
return a+b
print(add(1.0,2))
8.多个装饰器
def decorator_a(fun):
def inner_a(*args,**kwargs):
print('This is decorator a')
return fun(*args,**kwargs)
return inner_a
def decorator_b(fun):
def inner_b(*args,**kwargs):
print('This is decorator b')
return fun(*args,**kwargs)
return inner_b
@decorator_b
@decorator_a
def f(x):
print('This is testfunc')
return x*2
print(f(1))
9.装饰器的练习
练习:创建装饰器,打印被装饰的函数日志信息
创建装饰器, 要求如下:
1. 创建add_log装饰器, 被装饰的函数打印日志信息;
2. 日志格式为: [字符串时间] 函数名: xxx, 运行时间:xxx, 运行返回
值结果:xxx
import time
import functools
def add_log(fun):
@functools.wraps(fun)
def wrapper(*args,**kwargs):
start_time = time.time()
res = fun(*args,**kwargs)
end_time = time.time()
print('[%s] 函数名: %s,运行时间: %.6f,运行返回值结果: %d'
%(time.ctime(),fun.__name__,end_time-start_time,res))
return res
return wrapper
@add_log
def add(x,y):
time.sleep(1)
return x+y
add(1,10)