调用None的不存在函数
如果我把一个异常命名为一个变量,这个变量会有什么属性呢?比如说,
try:
None.nonexistent_function()
#return an AttributeError.
except Exception as ex:
self.assertEqual(__, ex.__class__.__name__)
在这个例子中,怎样才能让这个判断为真?我们怎么能知道这个异常的名称和类别呢?
这个问题是Python Koans的一部分,Python Koans是最近移植自Ruby Koans的。
2 个回答
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
对象,所以你需要自己测试剩下的部分。这样可以吗?
2
可以在这个在线环境中试试:
>>> 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'
>>>