python 装饰器
模板
1 | from functools import wraps |
使用场景
授权(Authorization)
1
2
3
4
5
6
7
8
9
10from functools import wraps
def requires_auth(f):
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
authenticate()
return f(*args, **kwargs)
return decorated日志
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17from functools import wraps
def logit(func):
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
def addition_func(x):
"""Do some math."""
return x + x
result = addition_func(4)
# Output: addition_func was called函数中嵌入装饰器
1 | from functools import wraps |
装饰器类
1 | from functools import wraps |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.