python中的嵌套try语句? [英] Nested try statements in python?

查看:57
本文介绍了python中的嵌套try语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好的方法来执行以下操作:

Is there a nicer way of doing the following:

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

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

It looks pretty nasty and I'd rather not do:

if hasattr(a, 'method1'):
    a.method1()
else if hasattr(a, 'method2'):
    a.method2()
else if hasattr(a, 'method3'):
    a.method3()
else:
    raise AttributeError

保持最高效率.

推荐答案

也许你可以试试这样的:

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

你可以这样称呼它:

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)

这篇关于python中的嵌套try语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆