我有点好奇在返回结果后是否可以在函数中做更多的工作。基本上我在处理输入后使用金字塔框架(它只是在 python 中编码)创建一个站点,我返回变量来呈现页面,但有时我想在呈现页面后做更多的工作。
例如,您访问我的网站并更新您的个人资料,而您只关心它是否成功,所以我输出一条消息说“成功!”但在那之后,我想获取您的更新并更新您的事件日志,更新您的 friend 事件流等。现在我正在做所有这些,然后返回您关心的结果状态,但我'我很好奇我是否可以这样做,以便用户更快地得到他们的响应。
我之前做过多处理,最坏的情况是我可能会派生一个线程来完成这项工作,但如果有一种方法可以在 return 语句之后完成工作,那就更简单了。
示例:
def profile_update(inputs):
#take updates and update the database
return "it worked"
#do maintenance processing now.
最佳答案
如果你从一个try-block返回,你仍然可以在return后做一些工作,finally-block会仍然被执行,例如:
def fun(x):
try:
return x * 20
finally:
print("Yay! I still got executed, even though my function has already returned!")
print(fun(5))
预期输出:
Yay! I still got executed, even though my function has already returned!
100
引用 the docs :
When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.
关于python - 有没有办法在返回声明之后做更多的工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11604699/