Nested try statements in python?

后端 未结 6 919
感动是毒
感动是毒 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:50

    If you are using new-style object:

    methods = ('method1','method2','method3')
    for method in methods:
        try:
            b = a.__getattribute__(method)
        except AttributeError:
            continue
        else:
            b()
            break
    else:
        # re-raise the AttributeError if nothing has worked
        raise AttributeError
    

    Of course, if you aren't using a new-style object, you may try __dict__ instead of __getattribute__.

    EDIT: This code might prove to be a screaming mess. If __getattribute__ or __dict__ is not found, take a wild guess what kind of error is raised.

提交回复
热议问题