调用函数或函数(python)

Call function or function (python)

我有4个功能。我希望我的代码执行第一个和第二个、第三个或第四个。我也想要至少一个(其中任何一个)无论如何,除非他们都失败了。 我最初的实施是:

try:
    function1(var)
except:
    pass
try:
    function2(var) or function3(var) or function4(var)
except:
    pass

如果 function2 不工作,它不会转到 function3,如何编码来解决这个问题?

如果确定一个函数的成功或失败,无论它是否引发异常,您都可以编写一个辅助方法,它会尝试调用一系列函数,直到一个成功的函数 returns .

#!/usr/bin/env python
# coding: utf-8

import sys

def callany(*funs):
    """
    Returns the return value of the first successfully called function
    otherwise raises an error.
    """
    for fun in funs:
        try:
            return fun()
        except Exception as err:
            print('call to %s failed' % (fun.__name__), file=sys.stderr)
    raise RuntimeError('none of the functions could be called')

if __name__ == '__main__':
    def a(): raise NotImplementedError('a')
    def b(): raise NotImplementedError('b')
    # def c(): raise NotImplementedError('c')
    c = lambda: "OK"

    x = callany(a, b, c)
    print(x)
    # call to a failed
    # call to b failed
    # OK

可以通过添加对函数参数的支持来改进上面的玩具实现。

可运行代码段:https://glot.io/snippets/ehqk3alcfv

如果函数通过返回布尔值指示成功,您可以像在普通布尔表达式中一样使用它们。