相关疑难解决方法(0)

python中的嵌套try语句?

有没有更好的方法来做到以下几点:

try:
    a.method1()
except AttributeError:
    try:
        a.method2()
    except AttributeError:
        try:
            a.method3()
        except AttributeError:
            raise
Run Code Online (Sandbox Code Playgroud)

它看起来很讨厌,我宁愿不这样做:

if hasattr(a, 'method1'):
    a.method1()
else if hasattr(a, 'method2'):
    a.method2()
else if hasattr(a, 'method3'):
    a.method3()
else:
    raise AttributeError
Run Code Online (Sandbox Code Playgroud)

保持最高效率.

python try-catch

30
推荐指数
3
解决办法
3万
查看次数

标签 统计

python ×1

try-catch ×1