Higher Order Functions and Closures in Python
2 min readMar 22, 2022
Hope you all understand ,What is Functions and basics of OOPs. Now, let us understand what is a higher order function….
- A
Higher Order function
is a function, which is capable of doing any one of the following things: - It can be functioned as a
data
and be assigned to a variable. - It can accept any other
function as an argument
. - It can return a
function as its result
. - The ability to build Higher order functions, allows a programmer to create Closures, which in turn are used to create Decorators.
Function as a Data
Example :
Function as an Argument
Example:
Returning a Function
Example
- You can observe from the output that the return value of “mainFunc” function is the return value of ‘insideMainFunc’ function i.e ‘Dmusketeer’.
Now focus on below function
- Parenthesis after the
insideMainFunc
function are removed so that themainFunc
function returnsinsideMainFunc
function.
Closures
In simplest terms, a Closure is a function returned by a higher order function
, whose return value depends on the data associated with the higher order function.
Example
Explanation
- You can observe from the example that the closure functions
n1
hold the data passed to enclosing function,fullName
, during their creation. - The first closure function,
n1
binds the valueDmus
to argumentfname
and when called with an argumentlname
, it executes the body oflName
function and returns the sum offname
andlname
.
conclusion
I try to explain higher Order function and closure in simplest form through example. If You find some insight from this article then follow me and share with your friends and Keep Learning……………