python - 如何确定AttributeError指的是哪个属性?

标签 python exception error-handling standard-library anti-patterns

当我请求一个不存在的python对象的属性时,我得到了AttributeError,但是在错误对象的字段中找不到所请求属性的名称。唯一提及请求的属性名称的位置是错误的args成员。

在我看来,解析错误消息以获取缺少的属性的名称有点烦。有什么方法可以在不解析错误消息的情况下获取缺少属性的名称?

演示:

class A:
    def f(self):
        print('in A')


class B:
    pass


class C:
    def f(self):
        print('in C')
        raise AttributeError()


def call_f(o):
    try:
        o.f()
    except AttributeError as e:
        # instead of e.args[0].endswith("'f'") it would be nice to do
        # e.missing_attribute == 'f'
        if e.args and e.args[0].endswith("'f'"):
            print(e.args) # prints ("'B' object has no attribute 'f'",)
        else: raise

if __name__ == '__main__':
    a = A()
    b = B()
    c = C()

    call_f(a)
    call_f(b)
    call_f(c)

最佳答案

当前没有统一的方法来执行此操作。该功能已在PEP 473中建议
仍处于草稿形式

关于python - 如何确定AttributeError指的是哪个属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40722921/

相关文章:

python - 将特定的选定列提取到新的 DataFrame 作为副本

java - 管理多个 catch block 中的重复代码

c# - 运行 Visual Studio 2019 React 模板时出现错误 400

c# - Unity C#中的更多脚本问题

python - tf.contrib.learn 快速入门 : - Changing n_classes to 2 does not work

python - 如何将变化的数据读入字典?

java - CMT 无状态 bean 中的异常处理

php - fatal error : Cannot use object of type MongoCursor as array

python - Keras 顺序模型损失不会减少并且在所有时期都保持不变

exception - Ada 83 异常是否包括资源清理?