如何将对象的函数名称作为参数传递

时间:2019-11-21 19:03:17

标签: python

我想做的是这样的:

def custom_logger(user_logger, log_level, *args, **kwargs):    
    # do some stuff..
    user_logger.log_level(*args, **kwargs)

或类似这样:

def create_logger(module_name, log_level=DEBUG):
    logger = logging.getLogger(module_name)
    logger.setLevel(logging.log_level)

如何实现这样的目标?因为它将清理很多东西。

1 个答案:

答案 0 :(得分:1)

您可以使用getattr函数通过名称获取属性:

def custom_logger(user_logger, log_level, *args, **kwargs):    
    log = getattr(user_logger, log_level) # or log_level.lower() if log_level is in upper case
    # do some stuff..
    log(*args, **kwargs)

def create_logger(module_name, log_level=DEBUG):
    logger = logging.getLogger(module_name)
    logger.setLevel(getattr(logging, log_level))