有没有办法在 return 语句之后做更多的工作? [英] Is there a way to do more work after a return statement?

查看:46
本文介绍了有没有办法在 return 语句之后做更多的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点好奇,是否可以在返回结果后在函数中做更多的工作.基本上,我在处理输入后使用金字塔框架(它只是在 python 中编码)创建一个站点,我返回变量以呈现页面,但有时我想在呈现页面后做更多的工作.

I was a bit curious if I could do more work in a function after returning a result. Basically I'm making a site using the pyramid framework(which is simply coding in python) after I process the inputs I return variables to render the page but sometimes I want to do more work after I render the page.

例如,您来到我的网站并更新您的个人资料,您只关心它是否成功,所以我输出一条消息说成功!"但在那之后,我想获取你的更新并更新我的活动日志,更新你所做的事情,更新你的朋友活动流等.现在我正在做所有这些,然后我返回你关心的结果状态,但我'我很好奇我是否可以这样做,以便用户更快地得到他们的回复.

For example, you come to my site and update your profile and all you care about is that its successful so I output a message saying 'success!' but after that done I want to take your update and update my activity logs of what your doing, update your friends activity streams, etc.. Right now I'm doing all that before I return the result status that you care about but I'm curious if I can do it after so users get their responses faster.

我之前做过多处理,在最坏的情况下,我可能只是 fork 一个线程来完成这项工作,但如果有一种方法可以在 return 语句之后完成工作,那会更简单.

I have done multi-processing before and worst case I might just fork a thread to do this work but if there was a way to do work after a return statement then that would be simpler.

示例:

def profile_update(inputs):
  #take updates and update the database 
  return "it worked"
  #do maintainence processing now..

推荐答案

不,不幸的是,一旦你点击了 return 语句,你就会从函数/方法中返回(有或没有返回值)).

No, unfortunately, once you hit the return statement, you return from the function/method (either with or without a return value).

来自 返回文档:

return 以表达式列表(或 None)作为返回值保留当前函数调用.

return leaves the current function call with the expression list (or None) as return value.

您可能想查看生成器函数和 yield 语句,这是一种从函数返回值并继续处理并准备在下次调用该函数时返回的另一个值的方法.

You may want to look into generator functions and the yield statement, this is a way to return a value from a function and continue processing and preparing another value to be returned when the function is called the next time.

这篇关于有没有办法在 return 语句之后做更多的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆