模板

1
2
3
4
5
6
7
8
9
10
11
from functools import wraps
def decorator(f):
@warps(f):
def decorated(*args, **kwargs):
print('This is decorated')
return f(*args, **kwargs)
return decorated

@decorator
def func():
print('This is func')

使用场景

  • 授权(Authorization)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    from functools import wraps

    def requires_auth(f):
    @wraps(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
    17
    from functools import wraps

    def logit(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
    print(func.__name__ + " was called")
    return func(*args, **kwargs)
    return with_logging

    @logit
    def addition_func(x):
    """Do some math."""
    return x + x


    result = addition_func(4)
    # Output: addition_func was called

    函数中嵌入装饰器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from functools import wraps

def logit(logfile='out.log'):
def logging_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
with open(logfile, 'a') as opened_file:
opened_file.write(log_string + '\n')
return func(*args, **kwargs)
return wrapped_function
return logging_decorator

@logit()
def func1():
pass

@logit(logfile='func2.log')
def func2():
pass

装饰器类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from functools import wraps

class logit:
def __init__(self, logfile='out.log'):
self.logfile = logfile

def __call__(self, func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
with open(logfile, 'a') as opened_file:
opened_file.write(log_string + '\n')
self.notify()
return func(*args, **kwargs)
return wrapped_function

def notify(self):
pass

@logit()
def func1():
pass

@logit(logfile='func2.log')
def func2():
pass