优雅的方式来抽象多个函数调用?

时间:2009-07-07 20:16:01

标签: python function

示例:

>>> 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?也许在标准库的帮助下......没有重新发明轮子?

2 个答案:

答案 0 :(得分:5)

这样的东西?

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()在装饰函数之后调用任意数量的函数。您可能希望以不同的方式实现装饰器,具体取决于您想要的返回值 - 装饰函数中的原始值,所有函数结果的列表或者根本没有。

答案 1 :(得分:1)

您可以查看Python装饰器。

这里有一个清晰的描述:http://www.artima.com/weblogs/viewpost.jsp?thread=240808