场景:想定义一个可以接受参数的装饰器。
@decorator(x, y, z)
def func(a, b):
pass
等价
def func(a, b):
pass
func = decorator(x, y, z)(func)
假设你想写一个装饰器,给函数添加日志功能,同时允许用户指定日志的级别和其他的选项
from functools import wraps
import logging
def logged(level, name=None):
"""
Add logging to a function. level is the logging
level, name is the logger name. If name aren't
specified, they default to the function's module and name.
"""
def decorate(func):
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
log_name = name if name else func.__module__
log = logging.getLogger(log_name)
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
log.log(level, result)
return result
return wrapper
return decorate
@logged(logging.DEBUG)
def add(x, y):
return x + y
if __name__ == '__main__':
delete()
add(3, 2)
2019-02-19 15:10:27,849 - __main__ - DEBUG - 5
网友评论