python装饰器: 装饰器并不提供任何独特的功能,它所做的只是在函数定义语句上方,直接添加用来修改函数行为的装饰器函数。如果没有装饰器,也可以在定义函数之后,手动再封装一次该函数并重新赋值
@cache
def func():
...
类似于
def func():
...
func = cache(func)
7.1 基础知识
装饰器是通过包装目标函数来修改其行为的特殊高阶函数,绝大多数装饰器是利用函数的闭包实现的。
定义timer无参数装饰器,记录方法运行时间
def timer(func):
"""打印耗时"""
def decorated(*args, **kwargs):
st = time.perf_counter()
print('method run before')
ret = func(*args, **kwargs)
print('time cost: {} seconds'.format(time.perf_counter() - st))
return ret
return decorated
@timer
def test():
print('test method running')
#运行test输出
method run before
test method running
time cost: 2.9311000000000614e-05 seconds
给装饰器增加参数,通过参数判断是否打印参数方法。
def timer(print_arg=False):
"""
装饰器打印耗时
:param print_arg: 是否打印默认是 False
:return:
"""
def decorator(func):
"""打印耗时"""
def decorated(*args, **kwargs):
st = time.perf_counter()
print('method run before')
ret = func(*args, **kwargs)
if print_arg:
print(f'{func.__name__}, args:{args}, kwargs:{kwargs}')
print('time cost: {} seconds'.format(time.perf_counter() - st))
return ret
return decorated
return decorator
@timer(print_arg=True)
def test(p1,p2,**kwargs):
print('test method running')
##运行 test("name","age", **{"city":"wuhan"}) 输出
method run before
test method running
test, args:('name', 'age'), kwargs:{'city': 'wuhan'}
time cost: 4.03149999999991e-05 seconds
为了给装饰器增加参数,在原来的装饰器上又嵌套了一层。