Skip to main content
 首页 » 编程设计

python之在 Python 中将 *args 传递给 string.format

2025年05月04日17Free-Thinker

是否可以将 *args 传递给 string.format?我有以下功能:

@classmethod 
def info(cls, component, msg, *args): 
    """Log an info message""" 
    cls.__log(cls.Level.INFO, component, msg, args) 
 
@classmethod 
def __log(cls, level, component, msg, *args): 
    """Log a message at the requested level""" 
    logging.getLogger("local").log(level, " - ".join([component, msg.format(args)])) 

当我尝试使用 LogCapture 对其进行单元测试时,我得到以下信息:

def test_logWithArgs(self): 
    Logger.level(Logger.Level.INFO) 
    with LogCapture(level=Logger.Level.INFO) as lc: 
        Logger.info("MyComponent", "{0}", "TestArg") 
        lc.check(("local", "INFO", "MyComponent - TestArg")) 
 
 
AssertionError: Sequence not as expected: 
 
same: 
() 
 
first: 
(('local', 'INFO', 'MyComponent - TestArg'),) 
 
second: 
(('local', 'INFO', "MyComponent - (('TestArg',),)"),) 

请您参考如下方法:

我觉得你想做的是

msg.format(*args)