4

別の関数とは異なる結果を報告する関数を作成したいこれらの結果にはいくつかの例外がありますが、ifステートメントに変換できません

例 :

f(x)がValueErrorを発生させる場合、関数は文字列'Value'を返す必要がありますf(x)がTypeErrorを発生させる場合、関数は文字列'Typeを返す必要があります

しかし、Pythonでこれを行う方法がわかりません。誰かが私を助けることができますか?

私のコードは次のようなものです:-

def reporter(f,x):    

    if f(x) is ValueError():
        return 'Value'
    elif f(x) is E2OddException():
        return  'E2Odd'
    elif f(x) is E2Exception("New Yorker"):
        return 'E2'
    elif f(x) is None:
        return 'no problem'
    else:
        return 'generic'
4

3 に答える 3

16

Pythonで例外を処理する必要try-exceptがあります:-

def reporter(f,x): 
    try:
        if f(x):  
            # f(x) is not None and not throw any exception. Your last case
            return "Generic"
        # f(x) is `None`
        return "No Problem"
    except ValueError:
        return 'Value'
    except TypeError:
        return 'Type'
    except E2OddException:
        return 'E2Odd'
于 2013-01-25T06:59:36.557 に答える
2
def reporter(f,x):    
    try:
        if f(x) is None:
            return 'no problem'
        else:
            return 'generic'
    except ValueError:
        return 'Value'
    except E2OddException:
        return  'E2Odd'
    except E2Exception:
        return 'E2'
于 2013-01-25T07:00:22.070 に答える
0

try-except関数呼び出しを次のような構造に入れます

try:
    f(x)
except ValueError as e:
    return "Value"
except E20ddException as e:
    return "E20dd"

関数自体は例外を返しません。例外は外部でキャッチされます。

于 2013-01-25T06:59:14.653 に答える