In conclusion, the callback function is
A callback function is another function that is passed as an argument when calling a certain function in a computer program. [What is a callback function](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)
To put it more simply, it's a function used as an argument. No, do you understand? Somehow that. How do you use it? Lol
Let's look at a concrete example.
def callback_add(a, b):
print('{} + {} = {}'.format(a, b, a + b))
def callback_times(a, b):
print('{} × {} = {}'.format(a, b, a * b))
def handler(a, b, callback):
callback(a, b)
if __name__=='__main__':
handler(3, 5, callback_add)
handler(3, 5, callback_times)
3 + 5 = 8
3 × 5 = 15
Where * callback_add, callback_times * are callback functions. By the way, it seems that the function that calls the callback function is often described as handler. The merit of the callback function seems to be that the caller of the function can ** pass a predetermined process **.
Hmm ... ・ ・ ・ ** It's hard to understand how to use it **. When will you use it! !! !! !! !! !! !! It makes me want to be crazy. Lol So let's go one step further.
def f1():
name = 'Mike'
say_hello(name)
def say_hello(name):
print(name, 'Mr.,Hello!')
def say_bye(name):
print(name, 'Mr.,goodbye!')
def f2():
name = 'Mike'
say_bye(name)
if __name__=='__main__':
f1()
f2()
Mike,Hello!
Mike,goodbye!
If you build the logic that say_hello is in f1 without using the Callback function, you will have to create a new f2 again when you want to say something different with this name. And the more you increase, the more f3, f4. This is very inconvenient. You use the Callback function in such a case.
def f1(callback):
name = 'Mike'
callback(name)
def say_hello(name):
print(name, 'Mr. Hello!')
def say_bye(name):
print(name, 'Goodbye!')
if __name__=='__main__':
f1(say_hello)
f1(say_bye)
The above is the same example, but with the Callback function. It's insanely beautiful ... No matter how much you increase it, it will fit in f1 and you just need to increase the function of say_〇〇. If you haven't come to the pin yet, please glance at the upper and lower cords. And you can understand it by tracing it with your hand.
If you remember the Callback function, the range of functions will be greatly expanded.
[What is a callback function](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) Advantages of callback function
Recommended Posts