【发布时间】:2015-12-19 21:56:48
【问题描述】:
我正在关注 Python 文档的 try/except 并做出以下努力:
def profile_check(self):
try:
profile = self.profile_type
return profile
except TypeError:
...
self.profile_type 是 Django 模型中的一个字段,在这种情况下不存在(因此它返回为 None)。但是,似乎缺少一些东西,因为它永远不会继续执行 except 的操作,而是立即抛出 TypeError 异常:
>>> a.profile_check()
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'NoneType' object is not callable
这是我第一次尝试使用 try-catch,所以我知道这是基本的东西。
【问题讨论】:
-
您确定您发布的代码是引发错误的部分吗?
-
什么是
a?看起来a.profile_check是None。 -
异常只能在
try块中被捕获。如果你一开始就没有输入它,那么...... -
a是在此尝试中填写self的数据库对象。我知道它发生在 try 块中,因为它会在设置配置文件变量之前打印一条语句,而不是之后。