In Python, it is possible to return a function from another function. This can be useful when you want to create a function that returns a specialized version of another function with specific parameters or settings.
Here's an example of returning a function:
def add_numbers(n): def inner_function(x): return x + n return inner_functionadd_five = add_numbers(5) # returns a function that adds 5 to its inputadd_ten = add_numbers(10) # returns a function that adds 10 to its inputprint(add_five(3)) # Output: 8print(add_ten(3)) # Output: 13 |
In this example, add_numbers is a function that takes one parameter n and returns another function inner_function. inner_function takes one parameter x and adds n to it, which is defined in the outer function's scope.
When add_numbers is called with an argument of 5, it returns inner_function with n set to 5. This returned function is assigned to the variable add_five. We can then call add_five with an argument of 3, which returns the result of 3 + 5, or 8.
Similarly, when add_numbers is called with an argument of 10, it returns inner_function with n set to 10. This returned function is assigned to the variable add_ten. We can then call add_ten with an argument of 3, which returns the result of 3 + 10, or 13.
Returning functions can be useful when you need to create a function with a specific behavior that depends on the input parameters. It can make the code more modular and reusable.