如何编写一个简单的回调函数? [英] 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))
我在执行该命令时会收到它:
I receive this when I execute it:
Sum = 3
Add any two digits.
为什么加任意两位数字
在总和= 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
回调
本身无济于事;它接受参数- def callback(a,b):
callback
on its own doesn't do anything; it accepts parameters - def callback(a, b):
您做了 callback(1,2)
首先将调用该函数,从而打印 Sum = 3
。
The fact that you did callback(1, 2)
first will call that function, thereby printing Sum = 3
.
由于回调
不返回任何显式值,因此返回为 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(sum):
print("Sum = {}".format(sum))
def main(a, b, _callback = None):
print("adding {} + {}".format(a, b))
if _callback:
_callback(a+b)
main(1, 2, callback)
这篇关于如何编写一个简单的回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!