First Class functions in Python

PythonProgrammingServer Side Programming

In different programming languages, First Class objects are those objects, which can be handled uniformly. First Class objects can be stored as Data Structures, as some parameters of some other functions, as control structures etc. We can say that a function in Python is First Class Function, if it supports all of the properties of a First Class object.

What are the properties of First Class Functions?

  • It is an instance of an Object type
  • Functions can be stored as variable
  • Pass First Class Function as argument of some other functions
  • Return Functions from other function
  • Store Functions in lists, sets or some other data structures.

At first we will see how Functions in Python can be used as an object. In Python, a function can be assigned as variable. To assign it as variable, the function will not be called. So parentheses '()' will not be there.

Example code

Live Demo

def cube(x):
   return x*x*x
res = cube(5)
print(res)
my_cube = cube #The my_cube is same as the cube method
res = my_cube(5)
print(res)

Output

125
125

Now we will see how functions can be passed as argument of another functions. Here is the example.

Example code

def cube(x):
   return x*x*x
defmy_map(method, argument_list):
   result = list()
   for item in argument_list:
      result.append(method(item))
   return result
my_list = my_map(cube, [1, 2, 3, 4, 5, 6, 7, 8]) #Pass the function as argument
print(my_list)

Output

[1, 8, 27, 64, 125, 216, 343, 512]

Here is the third property of First Class Functions. In this case we will return one function from another function.

Example code

defcreate_logger(message):
   deflog():
      print('Log Message: ' + message)
   return log #Return a function
my_logger = create_logger('Hello World')
my_logger()

Output

Log Message: Hello World
raja
Published on 23-Nov-2018 06:05:54
Advertisements