How to write a simple callback function?

前端 未结 6 1930
我在风中等你
我在风中等你 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:36

    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)
    

提交回复
热议问题