为了账号安全,请及时绑定邮箱和手机立即绑定

Python中嵌套的try / except块是一种好的编程习惯吗?

Python中嵌套的try / except块是一种好的编程习惯吗?

繁华开满天机 2021-03-09 13:15:07
我正在编写自己的容器,该容器需要通过属性调用来访问内部的字典。容器的典型用法是这样的:dict_container = DictContainer()dict_container['foo'] = bar...print dict_container.foo我知道写这样的东西可能很愚蠢,但这就是我需要提供的功能。我正在考虑通过以下方式实现此目的:def __getattribute__(self, item):    try:        return object.__getattribute__(item)    except AttributeError:        try:            return self.dict[item]        except KeyError:            print "The object doesn't have such attribute"我不确定嵌套的try / except块是否是一个好习惯,所以另一种方法是使用hasattr()and has_key():def __getattribute__(self, item):        if hasattr(self, item):            return object.__getattribute__(item)        else:            if self.dict.has_key(item):                return self.dict[item]            else:                raise AttributeError("some customised error")或使用其中之一并尝试使用catch块,如下所示:def __getattribute__(self, item):    if hasattr(self, item):        return object.__getattribute__(item)    else:        try:            return self.dict[item]        except KeyError:            raise AttributeError("some customised error")哪个选项最适合Pythonic和优雅?
查看完整描述

4 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

您的第一个示例非常好。甚至官方的Python文档也推荐这种称为EAFP的样式。


就个人而言,我宁愿避免在不必要时嵌套:


def __getattribute__(self, item):

    try:

        return object.__getattribute__(item)

    except AttributeError:

        pass  # Fallback to dict

    try:

        return self.dict[item]

    except KeyError:

        raise AttributeError("The object doesn't have such attribute") from None

PS。has_key()已在Python 2中弃用了很长时间。请item in self.dict改用。


查看完整回答
反对 回复 2021-03-31
?
动漫人物

TA贡献1815条经验 获得超10个赞

虽然在Java中使用异常进行流控制确实是一个坏习惯(主要是因为异常迫使JVM收集资源(更多信息请参见此处)),但在Python中,您有两个重要的原则:鸭子类型和EAFP。基本上,这意味着鼓励您尝试以您认为可行的方式使用对象,并在情况并非如此时进行处理。


总之,唯一的问题是您的代码缩进过多。如果您愿意,请尝试简化一些嵌套,例如上面建议的答案中建议的lqc。


查看完整回答
反对 回复 2021-03-31
?
繁花不似锦

TA贡献1851条经验 获得超4个赞

请小心-在这种情况下,第一个finally被触摸,但也被跳过。


def a(z):

    try:

        100/z

    except ZeroDivisionError:

        try:

            print('x')

        finally:

            return 42

    finally:

        return 1



In [1]: a(0)

x

Out[1]: 1


查看完整回答
反对 回复 2021-03-31
  • 4 回答
  • 0 关注
  • 226 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信