首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python 带参数的装饰器

python 带参数的装饰器

作者头像
用户5760343
发布于 2019-12-12 18:03:39
发布于 2019-12-12 18:03:39
3.4K0
举报
文章被收录于专栏:sktjsktj

from functools import wraps import logging

def logged(level, name=None, message=None): """ Add logging to a function. level is the logging level, name is the logger name, and message is the log message. If name and message aren't specified, they default to the function's module and name. """ def decorate(func): logname = name if name else func.module log = logging.getLogger(logname) logmsg = message if message else func.name

代码语言:javascript
复制
    @wraps(func)
    def wrapper(*args, **kwargs):
        log.log(level, logmsg)
        return func(*args, **kwargs)
    return wrapper
return decorate

Example use

@logged(logging.DEBUG) def add(x, y): return x + y

@logged(logging.CRITICAL, 'example') def spam(): print('Spam!'

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • Example use
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档