How to write a simple callback function?

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

    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)
    

提交回复
热议问题