How to write a simple callback function?

喜欢而已 提交于 2020-01-12 07:17:12

问题


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.

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?


回答1:


callback on its own doesn't do anything. It accepts parameters.

The fact that you did callback(1, 2) first will call that function, thereby printing Sum = 3.

Since callback returns no explicit value, it is returned as None, so your code is equivalent to

callback(1, 2)
main()

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)



回答2:


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.

You might want to use a lambda and pass in the values.

#!/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)



回答3:


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)



回答4:


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)

main function is called with None as argument (So callback != None will always be False)




回答5:


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.



来源:https://stackoverflow.com/questions/40843039/how-to-write-a-simple-callback-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!