装饰器
装饰器定义:
把一个函数当作参数,返回一个替代版的函数
本质就是一个返回函数的函数
装饰器功能:
在不改变原函数的基础上,给函数增加功能
举例:
def desc(fun):
def add_info():
print('天天开心~')
fun()
return add_info
@desc
def login():
# print('天天开心~')
print('login...')
@desc
def logout():
print('logout...')
login()
logout()
函数对修改是封闭的,对扩展是开放的
import time
def f1(): #添加功能时,一般不会直接更改函数
print('This is a function')
def f2():
print('This is a function')
def print_current_time(func): #函数功能扩展
print(time.time())
func()
print_current_time(f1)
print_current_time(f2)
包含可变参数的装饰器
示例:
import time
def decorator(func):
def wrapper(*args): #可变参数
print(time.time())
func(*args)
return wrapper
@decorator
def f1(func_name):
print('This is a function ' + func_name)
@decorator
def f2(func_name1,func_name2):
print('This is a function ' + func_name1)
print('This is a function ' + func_name2)
f1('test')
f2('test1','test2')
结果:
包含关键字参数的装饰器
import time
def decorator(func):
def warpper(*args,**kwargs):
print(time.time())
func(*args,**kwargs)
return warpper
@decorator
def f1(func_name):
print('This is a function ' + func_name)
@decorator
def f2(func_name1,func_name2):
print('This is a function ' + func_name1)
print('This is a function ' + func_name2)
@decorator
def f3(func_name1,func_name2,**kwargs):
print('This is a function ' + func_name1)
print('This is a function ' + func_name2)
print(kwargs)
f1('test')
f2('test1','test2')
f3('test1','test2',a=1,b=2,c='redhat')
包含可变参数,关键字参数的装饰器
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,2)
多重装饰器
我们在使用装饰器时,为了满足需求,可以使用两个不冲突的装饰器对同一个函数进行装饰我们称之为多重装饰器
多重装饰器装饰时的顺序为从内到外,执行时从外到内。总的来说就是离函数近的先装饰后执行
示例:
def decorator_a(fun):
print('Get in decorator_a')
def inner_a(*args, **kwargs):
print('Get in inner_a')
res = fun(*args, **kwargs)
return res
return inner_a
def decorator_b(fun):
print('Get in decorator_b')
def inner_b(*args, **kwargs):
print('Get in inner_b')
res = fun(*args, **kwargs)
return res
return inner_b
@decorator_a
@decorator_b
def f(x):
print('Get in f')
return x * 2
f(2)
结果:
根据装饰器的定义,在执行f(2)时,如果装饰器存在先执行dectorator_b装饰器
由于装饰器b的返回结果为执行至dectorator_b的内层函数,根据装饰器定义,装饰器实质内层变成了dectorator_b(f)方法,而执行内层方法时仍然会被上层装饰器所影响,所以内层装饰器执行的顺序会时从上而下,装饰从下而上,直至无装饰器
装饰器练习
用装饰器实现一个函数记时器
import time
import random
import string
import functools
li = [random.choice(string.ascii_letters) for i in range(100)]
print(li)
def Timer(fun):
"""这是一个装饰器Timer"""
def wrapper(*args,**kwargs):
"""这是一个wrapper函数"""
start_time = time.time() #执行函数前的记时
res = fun(*args,**kwargs)
end_time = time.time() #执行函数后的记时
print('运行时间为: %.5f' %(end_time - start_time)) #打印执行函数所用的时间
return res
return wrapper
@Timer
def con_add():
s = ''
for i in li:
s += (i + ',')
print(s)
@Timer
def join_add():
print(','.join(li))
@Timer
def fun_list(n):
"""这是fun_list函数"""
return [i * 2 for i in range(n)]
@Timer
def fun_map(n):
return list(map(lambda x:x*2,range(n)))
con_add()
join_add()
print(fun_list(100))
print(fun_map(100))