我必须从AttributeError中提取名称。我:
x = 10
try:
x.append(20)
except AttributeError as e:
print(f"name of Atrribute is: {e}")
和结果:
name of Atrribute is: 'int' object has no attribute 'append'
我需要'追加',谢谢!
您可以在空格处拆分消息并取最后一个元素。然后从该元素中剥离'
。
x = 10
try:
x.append(20)
except AttributeError as e:
attribute_name = str(e).split()[-1].strip("'")
print(f"name of Atrribute is: {attribute_name}")
输出为name of Atrribute is: append
。
请注意,如果Python决定在未来的版本中传递更改的消息,则可能会中断此操作。
对于python >= 3.10
,AttributeError
的实例具有name
和obj
属性:
>>> try:
... 'spam'.ham
... except AttributeError as e:
... print(f'{e.name=}; {e.obj=}')
...
e.name='ham'; e.obj=spam
如果你手动raise AttributeError
,它的name
和obj
将是None
如果你想自己触发AttributeError
,你可以手动设置name
和obj
,例如
class Readonly:
def __setattr__(self, name, _=None):
e = AttributeError(f'{type(self).__name__} instance is readonly')
try:
e.name, e.obj = name, self
raise e from None
finally:
del e
__delattr__ = __setattr__