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(callback=None):
print('Add any two digits.')
if callback != None:
callback
main(callback(1, 2))
I receive this when I execute it:
Sum = 3
Add any two digits.
Why Add any two digits
is after Sum = 3
? I guess it is because the callback function executes first. How to execute the callback function after all other code in main()
executed?
A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.
Example: Using a Callback FunctionThe sayName() function is passed as an argument to the greet() function. The setTimeout() method executes the greet() function only after 2 seconds. However, the sayName() function waits for the execution of the greet() function.
A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.
In this code
if callback != None:
callback
callback
on its own doesn't do anything; it accepts parameters - def callback(a, b):
The fact that you did callback(1, 2)
first will call that function, thereby printing Sum = 3
, and then main()
gets called with the result of the callback
function, which is printing the second line
Since callback
returns no explicit value, it is returned as None
.
Thus, your code is equivalent to
callback(1, 2)
main()
You could try not calling the function at first and just passing its handle.
def callback(n):
print("Sum = {}".format(n))
def main(a, b, _callback = None):
print("adding {} + {}".format(a, b))
if _callback:
_callback(a+b)
main(1, 2, callback)
Here's what you wanted to do :
def callback(a, b):
print('Sum = {0}'.format(a+b))
def main(a,b,f=None):
print('Add any two digits.')
if f is not None:
f(a,b)
main(1, 2, callback)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With