您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

您的第一个例子很好。甚至官方的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 2022/1/1 18:31:57 有225人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶