How to write a simple callback function?

2020-06-03 05:29发布

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?

5条回答
戒情不戒烟
2楼-- · 2020-06-03 05:57

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)
查看更多
爷的心禁止访问
3楼-- · 2020-06-03 06:00

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)

查看更多
Evening l夕情丶
4楼-- · 2020-06-03 06:01

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)
查看更多
Explosion°爆炸
5楼-- · 2020-06-03 06:04

In this code

if callback != None:
    callback

callback on its own doesn't do anything; it accepts parameters - def callback(a, b):

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.

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)
查看更多
何必那么认真
6楼-- · 2020-06-03 06:05

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.

查看更多
登录 后发表回答