Python 如何写一个简单的回调函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40843039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write a simple callback function?
提问by srgbnd
Python 2.7.10
蟒蛇 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.
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?
为什么Add any two digits
是后Sum = 3
?我猜是因为回调函数先执行。执行完所有其他代码后如何执行回调函数main()
?
回答by OneCricketeer
In this code
在这段代码中
if callback != None:
callback
callback
on its own doesn't do anything; it accepts parameters - def callback(a, b):
callback
它自己不做任何事情;它接受参数 -def callback(a, b):
The fact that you did callback(1, 2)
first will call that function, thereby printing Sum = 3
.
您callback(1, 2)
首先执行的事实将调用该函数,从而打印Sum = 3
.
Since callback
returns no explicit value, it is returned as None
.
由于不callback
返回显式值,因此返回为None
。
Thus, your code is equivalent to
因此,您的代码等效于
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)
回答by erip
As mentioned in the comments, your callback is called whenever it's suffixed with open and close parens; thus it's called when you pass it.
正如评论中提到的,只要以 open 和 close 括号为后缀,就会调用您的回调;因此当你通过它时它会被调用。
You might want to use a lambda and pass in the values.
您可能想要使用 lambda 并传入值。
#!/usr/bin/env python3
def main(callback=None, x=None, y=None):
print('Add any two digits.')
if callback != None and x != None and y != None:
print("Result of callback is {0}".format(callback(x,y)))
else:
print("Missing values...")
if __name__ == "__main__":
main(lambda x, y: x+y, 1, 2)
回答by Eric Duminil
Here's what you wanted to do :
这是你想要做的:
def callback(a, b):
print('Sum = {0}'.format(a+b))
def main(a,b,f=None):
print('Add any two digits.')
if f != None:
f(a,b)
main(1, 2, callback)
回答by ettanany
Your code is executed as follows:
您的代码执行如下:
main(callback(1, 2))
callback
function is called with (1, 2)
and it returns None
(Without return statement, your function prints Sum = 3
and returns None
)
callback
函数被调用(1, 2)
并返回None
(没有返回语句,你的函数打印Sum = 3
并返回None
)
main
function is called with None
as argument (So callback != None
will always be False
)
main
函数被None
作为参数调用(所以callback != None
将永远是False
)
回答by farsil
The problem is that you're evaluating the callback before you pass it as a callable. One flexible way to solve the problem would be this:
问题是您在将回调作为可调用对象传递之前对其进行评估。解决问题的一种灵活方法是:
def callback1(a, b):
print('Sum = {0}'.format(a+b))
def callback2(a):
print('Square = {0}'.format(a**2))
def callback3():
print('Hello, world!')
def main(callback=None, cargs=()):
print('Calling callback.')
if callback != None:
callback(*cargs)
main(callback1, cargs=(1, 2))
main(callback2, cargs=(2,))
main(callback3)
Optionally you may want to include a way to support keyword arguments.
(可选)您可能希望包含一种支持关键字参数的方法。