A callback function is a function that is specified in advance so that it will be executed during the execution of the called function in the program. http://e-words.jp/w/%E3%82%B3%E3%83%BC%E3%83%AB%E3%83%90%E3%83%83%E3%82%AF%E9%96%A2%E6%95%B0.html
It is also sometimes described as a function passed as a function argument.
It is a linked article http://qiita.com/pocket8137/items/df5afba90b51e90587a5 First, define a function that calls the callback function.
def handler(func,*args):
return func(*args)
The first argument is a function pointer and the second argument is a variable argument. The argument of the callback function is received as the second argument.
And define the callback function
def say_hello(name):
print("Hello!!")
print(name)
Call. By the way, in Python, the function pointer is pointed to by not adding () to the function name.
if __name__ == "__main__":
callback = say_hello
#say to callback_Stores hello object ID
handler(callback, "moroku0519")
Execution result
Hello!!
moroku0519
In my case, there were occasions when I wanted to separate the functions used. Therefore, I defined a dictionary that stores the object ID.
def handler(func, *args):
return func(*args)
def function1(hoge):
return hoge
def function2(hoge, huga):
return hoge, huga
func_dic = {"func1": function1, "func2": function2}
result1 = handler(func_dic["func1"], hoge)
result2, result3 = handler(func_dic["func2"], hoge, huga)
Recommended Posts