修饰器定义:
英文名叫Decorator,主要用来对功能函数进行润色,在原有功能的基础上添加一些额外修饰。有些地方也叫做切面函数,即对功能函数切面穿插新功能。修饰器能减少代码冗余重复,使整体风格更加优雅高效。
常用场景:函数调用日志,函数性能统计,函数异常捕获,函数认证访问控制等。
使用方法:就是在方法名前面加一个@XXX注解来为这个方法装饰一些东西。
1,不带参数的修饰器
##在函数调用前后答应调用记录
def func_decorator(func):
def wrapper(*args, **kwargs):
func_name = func.__name__
print(' '.join(["before", func_name, "is called"]))
resp = func(*args, **kwargs)
print(' '.join(["after", func_name, "is called"]))
return resp
return wrapper
@func_decorator ##@func_decorator即为我们预先定义的修饰器
def test_01(*args, **kwargs): ##功能函数
print(args)
print(kwargs)
test_01("hello", "welcome")
运行后,我们将看到如下输出:
before test_01 is called
('hello', 'welcome')
{}
after test_01 is called
修饰器@func_decorator功能等同于func=func_decorator(func)
其效果和如下实现相同
##在函数调用前后答应调用记录
def func_decorator(func):
def wrapper(*args, **kwargs):
func_name = func.__name__
print(' '.join(["before", func_name, "is called"]))
resp = func(*args, **kwargs)
print(' '.join(["after", func_name, "is called"]))
return resp
return wrapper
# @func_decorator ##@func_decorator等同于func = func_decorator(func)
def test_01(*args, **kwargs): ##功能函数
print(args)
print(kwargs)
# test_01("hello", "welcome")
func_decorator(test_01)("hello", "welcome")
2,多个修饰器
import time
##在函数调用前后答应调用记录
def func_decorator_call(func):
def wrapper(*args, **kwargs):
func_name = func.__name__
print(' '.join(["before", func_name, "is called"]))
resp = func(*args, **kwargs)
print(' '.join(["after", func_name, "is called"]))
return resp
return wrapper
def func_decorator_time(func):
def wrapper(*args, **kwargs):
start_time = time.time()
print(' '.join(["before", str(start_time), " func start"]))
resp = func(*args, **kwargs)
end_time = time.time()
print(' '.join(["after", str(end_time), "func end"]))
return resp
return wrapper
@func_decorator_call
@func_decorator_time ###多个修饰器是按照由内到外的顺序,即最外层的修饰效果出现在最外层
def test_01(*args, **kwargs): ##功能函数
print(args)
print(kwargs)
test_01("hello", "welcome")
输出:
before wrapper is called
before 1536406178.534688 func start
('hello', 'welcome')
{}
after 1536406178.534733 func end
after wrapper is called
3,带参数的修饰器
def func_decorator_with_param(dec_tag, *dec_args, **dec_kwargs):##修饰器参数
print(" ".join(["the outer decorator tag :", dec_tag]))
def decorator(func): ##返回外层修饰器
start_time = time.time()
print(' '.join(["func start: ", str(start_time)]))
def wrapper(*args, **kwargs): ##内层封装
resp = func(*args, **kwargs)
return resp
print(' '.join(["func params: ", str(dec_args), str(dec_kwargs)]))
return wrapper
return decorator
@func_decorator_with_param(dec_tag="outer_tag" ,demo="decorator with param")
def test_02(*args, **k