猿问

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

我正在编写自己的容器,该容器需要通过属性调用来访问内部的字典。容器的典型用法是这样的:


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和优雅?


繁华开满天机
浏览 227回答 4
4回答

拉丁的传说

您的第一个示例非常好。甚至官方的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 NonePS。has_key()已在Python 2中弃用了很长时间。请item in self.dict改用。

动漫人物

虽然在Java中使用异常进行流控制确实是一个坏习惯(主要是因为异常迫使JVM收集资源(更多信息请参见此处)),但在Python中,您有两个重要的原则:鸭子类型和EAFP。基本上,这意味着鼓励您尝试以您认为可行的方式使用对象,并在情况并非如此时进行处理。总之,唯一的问题是您的代码缩进过多。如果您愿意,请尝试简化一些嵌套,例如上面建议的答案中建议的lqc。

繁花不似锦

请小心-在这种情况下,第一个finally被触摸,但也被跳过。def a(z):    try:        100/z    except ZeroDivisionError:        try:            print('x')        finally:            return 42    finally:        return 1In [1]: a(0)xOut[1]: 1
随时随地看视频慕课网APP

相关分类

Python
我要回答