![](/img/trans.png)
[英]AttributeError: 'Pipeline' object has no attribute 'get_feature_names
[英]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)
将错误转换为文本groups()
方法将从正则表达式中返回所有捕获的组,这些组用括号标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.