繁体   English   中英

从 AttributeError 获取 class 和属性名称

[英]Get class and attribute names from AttributeError

如何从 AttributeError 中获取 class 和缺少属性,例如当 AttributeError 说: 'NoneType' object has not attribute a时,我想得到"NoneType""a"

看起来您可以从AttributeError中检索的唯一内容是带有错误消息的字符串:

try:
    str.s
except AttributeError as err:
    error_message, = err.args
    print("Error message:", error_message)
    raise

要从 AttributeError获取类型信息,您可以使用正则表达式,因为您知道错误消息的格式:

import re

try:
    None.attr
except AttributeError as e:
    matches = re.match(r"'([^']*)' object has no attribute '([^']*)'", str(e))
    obj_type = matches.group(1)
    attr_name = matches.group(2)
    print(f"Object type: {obj_type}, attribute name: {attr_name}")
# Object type: NoneType, attribute name: attr
import re

try:
    # access attribute
except AttributeError as e:
    obj_type, attr_name = re.match(r"\'([a-zA-Z0-9\_]+)\' object has no attribute \'([a-zA-Z0-9\_]+)\'", str(e)).groups()
  • 首先使用str(e)将错误转换为文本
  • 然后,使用正则表达式模式读取 object 类型和您尝试访问的属性的名称。 groups()方法将从正则表达式中返回所有捕获的组,这些组用括号标记。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM