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

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

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 block 是否是一个好习惯,所以另一种方法是使用 hasattr()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")

或者像这样使用其中一个和一个 try catch block :

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

最佳答案

你的第一个例子很好。甚至官方 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

关于python - Python 中嵌套的 try/except block 是一种好的编程习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17015230/

相关文章:

python - 如何获取项目在列表中的位置?

python - 移动平均线或移动平均线

python - 是否可以使用 scikit-learn K-Means Clustering 指定

c - 如何从 C 中通过 PID 在 Linux 中计算进程的 CPU 使用率?

python - Pelican 3.3 pelican-quickstart 错误 "ValueE

linux - 是否可以在文件名中使用 "/"?

linux - 在linux中用制表符替换空格

python - Python 3 的图像库

linux - POSIX 异步 I/O (AIO) 的现状如何?

linux - 工控机性能: Named Pipe vs Socket