A function that is passed as an argument to another function.
The C language example on the following site is easy to understand. A callback function is assigned to the function pointer and passed as an argument.
http://shiroibanana.blogspot.jp/2012/09/callback.html
#include<stdio.h>
typedef void (* FUNC_POINTER)(char *);
//Cobuck function 1
void callback1(char *s){
printf("%s\n",s);
}
//Callback function 2
void callback2(char *s){
printf("[");
printf("%s",s);
printf("].\n");
}
//A function that calls a callback function
void func(char *s,FUNC_POINTER p){
//Call the callback function
p(s);
}
int main(){
FUNC_POINTER p;
p = callback1;
//Call callback function 1
func("Cobuck function 1",p);
p = callback2;
//Call callback function 2
func("Cobuck function 2",p);
return 0;
}
Execution result.
Cobuck function 1
[Cobuck function 2].
An example of using a callback function in python. It seems that the function that calls the callback function is often described as handler ↓
def handler(func,*args):
return func(*args)
http://www.phactory.jp/cms/blog/post/admin/2010/02/python_funcpointer/
As a flow,
# -*- coding: utf-8 -*-
def handler(func,*args):
return func(*args)
def callback1(message1):
print("%s" % message1)
def callback2(message1, message2):
print("%s, %s" % ( message1, message2) )
# main
if __name__ == "__main__":
#Callback function assignment
call = callback1
#Handler execution:Callback function call
handler(call, "message1")
#Callback function assignment
call = callback2
#Handler execution:Callback function call
handler(call, "message1", "message2")
Execution result.
message1
message1, message2
The member "func" in the class has a variable that acts as a function pointer, but basically the same thing is done.
# -*- coding: utf-8 -*-
class Callbacker():
def __init__(self, func):
self.func = func
def handler(self, *args):
self.func(*args)
def callback1(message1):
print '%s' % message1
def callback2(message1, message2):
print("%s, %s" % ( message1, message2) )
# main
if __name__ == "__main__":
#Callback function assignment
callback = Callbacker(callback1)
print (type(callback.func))
print ("callback.func "),
print (callback.func)
print ("callback1 "),
print (callback1)
#Handler execution:Callback function call
callback.handler("message1")
print ("")
#Callback function assignment
callback.func = callback2
print (type(callback.func))
print ("callback.func "),
print (callback.func)
print ("callback2 "),
print (callback2)
#Handler execution:Callback function call
callback.handler("message1", "message2")
Execution result
<type 'function'>
callback.func <function callback1 at 0x7fcff9c8a9b0>
callback1 <function callback1 at 0x7fcff9c8a9b0>
message1
<type 'function'>
callback.func <function callback2 at 0x7fcff9c8ab18>
callback2 <function callback2 at 0x7fcff9c8ab18>
message1, message2
A callback function is a function that is passed as an argument to another function.
Basically
Recommended Posts