Nested try statements in python?

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

    Perhaps you could try something like this:

    def call_attrs(obj, attrs_list, *args):
        for attr in attrs_list:
            if hasattr(obj, attr):
                bound_method = getattr(obj, attr)
                return bound_method(*args)
    
        raise AttributeError
    

    You would call it like this:

    call_attrs(a, ['method1', 'method2', 'method3'])
    

    This will try to call the methods in the order they are in in the list. If you wanted to pass any arguments, you could just pass them along after the list like so:

    call_attrs(a, ['method1', 'method2', 'method3'], arg1, arg2)
    

提交回复
热议问题