First class functions are functions which can be returned from another function, which can be passed as parameters into another function.

Properties of first class function -:

  1. Store the function in a variable and execute it later by adding paranthesis.
  2. Return one function from another function.
  3. We can pass the function as parameter

Let’s see the properties of first class function through example.

1. First class function – How to create a variable of a function and then pass the args.

In [1]:

def print_name(name):
    return name

print(print_name('Robofied'))

Out[1]:

Robofied

In [2]:

## Storing function in a variable
store_var = print_name 

## It will not print any value, it gives information about function
store_var

Out[2]:

<function __main__.print_name(name)>

In [3]:

store_var('Rajesh!')

Out[3]:

'Rajesh!'

2. First class function – How to return function from another function?

In [4]:

def employee_name(name):
    
    ## Inner function
    def office_hours(start_time,finish_time):
        return ('Hi '+ str(name)+ '! Your office hours will be ' + str((int(finish_time.split(':')[0]) - int(start_time.split(':')[0])))+ 
              ' hours.')
    
    ## Returning office_hours function from employee_name function
    return office_hours
        

In [5]:

e_n = employee_name('Rajesh')

## employee_name function is returning office hours function so, it will return function name
e_n

Out[5]:

<function __main__.employee_name.<locals>.office_hours(start_time, finish_time)>

In [6]:

## By passing the arguments, will get the results.
e_n('10:00','18:00')

Out[6]:

'Hi Rajesh! Your office hours will be 8 hours.'

3. First class function – How to pass function as an argument.

In [7]:

def employee_name(fun , name, s, f):
    
    message = fun(name,s,f)
    print(message)

In [8]:

## it will be pass as an argument
def office_hours(name,start_time,finish_time):
    
    return ('Hi '+ str(name)+ '! Your office hours will be ' + str((int(finish_time.split(':')[0]) - int(start_time.split(':')[0])))+ 
              ' hours.')

In [9]:

employee_name(office_hours,'Rajesh','10:00','18:00')

Hi Rajesh! Your office hours will be 8 hours.

So, theses are some properties of first class function, in upcoming blogs will see how to use these first class function properties in closures etc.

Hope, you enjoyed reading this blog. Stay tuned with us! Keep learning Python with us!

Leave a Comment

Your email address will not be published. Required fields are marked *