如果我将一个异常命名为变量,该变量会保存哪些属性?例如,
try:
None.nonexistent_function()
#return an AttributeError.
except Exception as ex:
self.assertEqual(__, ex.__class__.__name__)
在这种情况下,使断言成为真的必要吗?如何确定例外的名称和类别?
这个问题是Python Koans的一部分,最近是Ruby Koans的一个端口。
答案 0 :(得分:2)
在REPL尝试:
>>> try: None.foo()
... except Exception as ex: pass
...
>>> # ex is still in scope, so we can play around with it and find out for ourselves:
... ex.__class__.__name__
'AttributeError'
>>>
答案 1 :(得分:0)
嗯...使用Python的命令行,我得到:
>>> try:
... None.nonexistent_function()
... #return an AttributeError.
... except Exception as ex:
... print ex.__class__.__name__
...
AttributeError
>>>
让我们试试:
>>> try:
... None.nonexistent_function()
... #return an AttributeError.
... except Exception as ex:
... print 'AttributeError' == ex.__class__.__name__
...
True
我没有任何你的self
对象是方便的,所以你必须测试其余的。这对你有用吗?