如何确定AttributeError引用的属性?

2024-04-19 20:49:13 发布

您现在位置:Python中文网/ 问答频道 /正文

当我请求一个不存在的python对象的属性时,我得到了AttributeError,但是在error对象的字段中我没有找到请求的属性的名称。唯一提到请求属性名称的地方是错误的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)

Tags: 对象inself名称消息属性def错误