Since I figured out the callback function, my understanding of Python has gone to the next level

2022-11-22

Source: Uncle Mac Programming

This issue should be an old fan's request - three minutes to speak clearly what is the callback function (Callback Function).

"

Definition
A callback function is when a pointer (address) to a function is passed as an argument to another function, and that pointer is used to call the function it points to. A callback function is not called directly by the implementer of the function, but by another party when a specific event or condition occurs, in response to that event or condition.

"To put the above obscure concepts into one sentence, "

"

A callback function is a function that is passed as an argument.

"

Example
Write a function with a calculator function in three lines of code

def calculator(v1,v2,fn): result = fn(v1,v2) return result
But this calculator doesn't do anything, and 1+1 doesn't compute.

Then write an add function to find the sum of two numbers.

def calculator(v1,v2,fn): result = fn(v1,v2) return result def add(v1,v2): return v1 + v2 # Call calculator and calculate 1+1 print(calculator(1,1,add))
Output results.


The add function in the above code is called the callback function of the calculator.

Isn't it still pretty simple?

"

Then don't you still write the callback functions for subtraction, multiplication and division to increase the impression?

"

The difference between callback functions and recursive functions
A callback function is a function in which the "callback function" is passed in as an argument and is called inside the function.

A recursive function, on the other hand, is a function within a function that calls itself.

The difference between callback functions and higher-order functions
Remember the higher-order functions that appeared a few issues ago? Isn't the callback function kinda like it?

Recall the definition of a higher-order function.

"

Python's higher-order function is actually a function that accepts a function as an argument, or a function that returns a function as a result is a higher-order function (higher-order function).

"

And the definition of a callback function

"

A callback function is a function that is passed as an argument.

"

Any sense of the subtlety of this?

def calculator(v1,v2,fn): result = fn(v1,v2) return result def add(v1,v2): return v1 + v2
In the above code, the

calculator is a higher-order function, and add is a callback function.

More details ~

Finally
Thank you for your continued interest, I wonder if today's article is helpful to you?

Thanks for watching

Join Us

Company/Organization Name:

Company/Organization Site:

Candidate Name:

Candidate Job:

Tel:

Email:

Admission Remarks: (cause and appeal of admission)

Submit application