一、什么是装饰器?
装饰器:
把一个函数当作参数,返回一个替代版的函数
本质就是一个返回函数的函数
“在不改变原函数的基础上,给函数增加功能”
示例1:
def desc(fun):
def add_info(): # 实际功能函数
print('Hello world')
fun()
return add_info # 返回一个功能函数
@desc # 使用@语法糖的方式调用
def login():
print('login...')
@desc # 使用@语法糖的方式调用
def logout():
print('logout...')
login()
logout()
执行效果:
示例2:
#函数对修改是封闭的,对扩展是开放的
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():
print(time.time())
func()
return wrapper
@decorator
def f1():
print('This is a function...')
def f2():
print('This is a function...')
f1()
执行效果:
二、包含可变参数的装饰器
示例:
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)
执行效果: