修饰器定义了新的本地函数,该函数将调用原始函数
一、函数修饰器
1、原始版
def positive_result(function):
def wrapper(*args, **kwargs):
result = function(*args, **kwargs)
assert result >=0 , function.__name__+ "() result isn't >=0 "
return result
wrapper.__name__ == function.__name__
wrapper.__doc__ == function.__doc__
return wrapper
2、优化v1, 使用functools简化,只是简单装饰器,装饰器本身无法传入参数
import functools
def positive_result(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
print(args)
result = function(*args, **kwargs)
assert result >=0 , function.__name__+ "() result isn't >=0 "
return result
return wrapper
3、修饰器参数化,类似于@bounded(0, 5)
def bounded(minimum, maximum):
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
result = function(*args, **kwargs)
if result < minimum:
return minimum
elif result > maximum:
return maximum
return result
return wrapper
return decorator