How to write a simple callback function?

前端 未结 6 1945
我在风中等你
我在风中等你 2021-02-04 06:11

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(         


        
6条回答
  •  一个人的身影
    2021-02-04 06:31

    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.

提交回复
热议问题