How to write a simple callback function?

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

    This is an old post, but perhaps the following may be additional clarification on writing and using a callback function, especially if you wonder where it gets its arguments from and whether you can access its return values (if there is no way to get it from the function that takes the callback function).

    The following code defines a class CallBack that has two callback methods (functions) my_callback_sum and my_callback_multiply. The callback methods are fed into the method foo.

    # understanding callback
    
    class CallBack:
    
        @classmethod
        def my_callback_sum(cls, c_value1, c_value2):
            value = c_value1 + c_value2
            print(f'in my_callback_sum --> {c_value1} + {c_value2} = {value}')
            cls.operator = '+'
            return cls.operator, value
    
        @classmethod
        def my_callback_multiply(cls, c_value1, c_value2):
            value = c_value1 * c_value2
            print(f'in my_callback_multiply --> {c_value1} * {c_value2} = {value}')
            cls.operator = '*'
            return cls.operator, value
    
        @staticmethod
        def foo(foo_value, callback):
            _, value = callback(10, foo_value)
            # note foo only returns the value not the operator from callback!
            return value
    
    
    if __name__ == '__main__':
        cb = CallBack()
    
        value = cb.foo(20, cb.my_callback_sum)
        print(f'in main --> {value} and the operator is {cb.operator}')
    
        value = cb.foo(20, cb.my_callback_multiply)
        print(f'in main --> {value} and the operator is {cb.operator}')
    

    result:

    in my_callback_sum --> 10 + 20 = 30
    in main --> 30 and the operator is +
    in my_callback_multiply --> 10 * 20 = 200 
    in main --> 200 and the operator is *
    

    As you can see one value for the callback function c_value2 it gets from argument foo_value in foo and given in main the value 20, while c_value1 it gets internally from foo in this case the value 10 (and may be not clearly visible if foo is some method of a third party imported module, like pyaudio).

    The return value of the callback function functions can be retrieved by adding it to the namespace of the class CallBack, in this case cls.operator

提交回复
热议问题