装饰器封装一个函数,并且修改它的行为
蓝本规范:
from functools import wraps
def decorator_name(f):
@wraps(f) #保持f的函数名,参数列表等
def decorated(*args, **kwargs):
if not can_run:
return "Function will not run"
return f(*args, **kwargs)
return decorated #返回被修饰过的f函数
@decorator_name
def func():
return("Function is running")
can_run = True
print(func())
# Output: Function is running
can_run = False
print(func())
# Output: Function will not run
注意:@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。
应用场景:
检验授权、日志
装饰器类:
支持装饰器继承
参考:
https://www.runoob.com/w3cnote/python-func-decorators.html python 函数装饰器