Nested try statements in python?

后端 未结 6 916
感动是毒
感动是毒 2020-12-08 14:16

Is there a nicer way of doing the following:

try:
    a.method1()
except AttributeError:
    try:
        a.method2()
    except AttributeError:
        try:         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-08 14:56

    method = (
            getattr(a, 'method1', None) or
            getattr(a, 'method2', None) or
            getattr(a, 'method3')
            )
    method()
    

    This will first look for method1, then method2, then method3. The search will stop as soon as one of them is found. If none of the methods are found the last getattr will raise an exception.

提交回复
热议问题