如何写一个简单的回调函数? [英] How to write a simple callback function?
问题描述
Python 2.7.10
我编写了以下代码来测试一个简单的回调函数.
I wrote the following code to test a simple callback function.
def callback(a, b):
print('Sum = {0}'.format(a+b))
def main(callback=None):
print('Add any two digits.')
if callback != None:
callback
main(callback(1, 2))
我在执行时收到:
Sum = 3
Add any two digits.
为什么任意两位数
要在Sum = 3
之后?我猜是因为回调函数先执行.main()
中的所有其他代码执行完后如何执行回调函数?
Why Add any two digits
is after Sum = 3
? I guess it is because the callback function executes first. How to execute the callback function after all other code in main()
executed?
推荐答案
在这段代码中
if callback != None:
callback
callback
本身不做任何事情;它接受参数 - def callback(a, b):
callback
on its own doesn't do anything; it accepts parameters - def callback(a, b):
您执行 callback(1, 2)
的事实将首先调用该函数,从而打印 Sum = 3
,然后打印 main()
使用 callback
函数的结果被调用,该函数正在打印第二行
The fact that you did callback(1, 2)
first will call that function, thereby printing Sum = 3
, and then main()
gets called with the result of the callback
function, which is printing the second line
由于 callback
没有返回显式值,所以返回为 None
.
Since callback
returns no explicit value, it is returned as None
.
因此,您的代码等效于
callback(1, 2)
main()
解决方案
您可以尝试先不调用该函数,而仅传递其句柄.
Solution
You could try not calling the function at first and just passing its handle.
def callback(n):
print("Sum = {}".format(n))
def main(a, b, _callback = None):
print("adding {} + {}".format(a, b))
if _callback:
_callback(a+b)
main(1, 2, callback)
这篇关于如何写一个简单的回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!