Skip to main content
 首页 » 编程设计

python之抽象多个函数调用的优雅方式

2025年05月04日19artech

例子:

>>> def write_to_terminal(fmt, *args): 
...     print fmt % args 
>>> LOG = logging.getLogger(__name__) 
>>> info = multicall(write_to_terminal, LOG.info) 
>>> debug = multicall(write_debug_to_terminal, LOG.debug) 
>>> ... 
>>> info('Hello %s', 'guido') # display in terminal *and* log the message 

有没有一种优雅的方式来编写multicall?也许在标准库的帮助下......无需重新发明轮子?

请您参考如下方法:

是这样的吗?

def multicall(*functions): 
    def call_functions(*args, **kwds): 
        for function in functions: 
            function(*args, **kwds) 
    return call_functions 

如果您想汇总结果:

def multicall(*functions): 
    def call_functions(*args, **kwds): 
        return [function(*args, **kwds) for function in functions] 
    return call_functions 

编辑

建议使用装饰器;在那种情况下,它看起来像这样:

def appendcalls(*functions): 
    def decorator(decorated_function): 
        all_functions = [decorated_function] + list(functions) 
        def call_functions(*args, **kwds): 
            for function in all_functions: 
                function(*args, **kwds) 
        return call_functions 
    return decorator 
 
 
LOG = logging.getLogger(__name__) 
 
@appendcalls(LOG.info) 
def info(fmt, *args): 
    print fmt % args 
 
info('Hello %s', 'guido') 

appendcalls() 在装饰函数之后调用任意数量的函数。您可能希望以不同的方式实现装饰器,具体取决于您想要的返回值——来自装饰函数的原始值、所有函数结果的列表或什么都没有。