First Class Functions in Python
First-class objects in the language are handled the same everywhere. They can be stored in data structures, passed as arguments, or used in control structures. It is said that a programming language supports first-class functions if it considers functions as first-class objects. Python supports the concept of first-class functions.
Properties of functions of the first class:
A function is an instance of an object type.
- You can save the function in a variable. - You can pass a function as a parameter to another function. - You can return a function from a function. - You can store them in data structures such as hash tables, lists, ...
Examples illustrating first-class functions in Python
1. Functions are objects: Python functions are first class objects. In the example below, we assign a function to a variable. This assignment does not call a function. It takes the function object referenced by the scream, and creates a middle name that points to it, screaming.
# Python program to illustrate functions
Output:
HI
HI
- Functions can be passed as arguments to other functions: since functions are objects, we can pass them as arguments to other functions. Functions that can take other functions as arguments are also called higher-order functions. In the example below, we created a greet function that takes a function as an argument.
# Python program to illustrate functions
Output:
HI, I CREATED BY A FUNCTION PASSING AS AN ARGUMENT.
Hi, I am created by a function passed as an argument.
- Functions can return another function: since functions are objects, we can return a function from another function. In the example below, the create_adder function returns an adder function.
#Python program to illustrate functions
Output:
25
shanu khera
source share