我知道错误是什么:
AttributeError: 'NoneType' object has no attribute 'something'
意思是,但我想不通的是如何捕捉它。基本上我想检查我的对象是否已创建。
我想做这样的事情:
try:
test = self.myObject.values()
except:
print "Error happened"
但每次我这样做都会得到:
AttributeError: 'NoneType' object has no attribute 'values'
谁能告诉我如何捕捉这个?
最佳答案
您可以使用返回 True 或 False 的 hasattr(object, name) 方法。如果您尝试访问不存在的属性,您将始终收到异常。 https://docs.python.org/2/library/functions.html#hasattr
如果您仍然希望捕获异常,那么只需执行异常类型为“AttributeError”的 try/catch block
关于python - 如何捕捉 - 'NoneType' 对象没有属性 'something',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29107534/