这些是 Python 异常的属性,但我很难理解它们。Python 的文档对此似乎相当安静。我看了看文档,但很困惑。那么,这两者有什么区别,又是如何使用的呢?
编辑:在那张纸条上__traceback__
,如果有的话,它们有什么关系?
编辑3:我想我只是不明白__cause__
。我终于明白__traceback__
了__context__
。为什么不attribute_error.__cause__
参考AttributeError()
?
try:
raise NameError() from OSError
except NameError as name_error:
print('name_error.__cause__: %s' % repr(name_error.__cause__))
print('name_error.__context__: %s' % repr(name_error.__context__))
print('name_error.__traceback__: %s' % repr(name_error.__traceback__))
try:
raise AttributeError()
except AttributeError as attribute_error:
print('attribute_error.__cause__: %s' % repr(attribute_error.__cause__))
print('attribute_error.__context__: %s' % repr(attribute_error.__context__))
print('attribute_error.__traceback__: %s' % repr(attribute_error.__traceback__))
raise attribute_error from IndexError
这输出
name_error.__cause__: OSError()
name_error.__context__: None
name_error.__traceback__: <traceback object at 0x000000000346CAC8>
attribute_error.__cause__: None
attribute_error.__context__: NameError()
attribute_error.__traceback__: <traceback object at 0x000000000346CA88>
Traceback (most recent call last):
File "C:\test\test.py", line 13, in <module>
raise attribute_error from IndexError
File "C:\test\test.py", line 8, in <module>
raise AttributeError()
AttributeError