2016-08-22 55 views
0

我有4個函數。我希望我的代碼執行第一個,第二個,第三個或第四個。除非他們全都失敗,否則我至少也要一個(他們中的任何一個)。 我最初的實施是:調用函數或函數(python)

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

如果函數2不起作用,它不會去功能3,怎麼可能這個編碼考慮是什麼?

回答

2

如果確定函數失敗的成功與否,是否引發異常,您可以編寫一個助手方法,它會嘗試調用函數列表,直到成功函數返回。

#!/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

如果功能指示返回一個布爾值的成功,你可以使用它們,就像在一個普通的布爾表達式。