First class functions in Python

Python Methods and Functions

First class function properties:

  • A function is an instance of type Object.
  • You can store a 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 are assigning a function to a variable. This assignment does not call the function. It takes the function object referenced by shout and creates a second name pointing to it, yell.

# Python program to illustrate functions
# can be viewed as objects

def shout ( text):

return text. upper ()

 

print shout ( 'Hello' )

 

yell = shout

 

print yell ( 'Hello' )

Exit

 HELLO HELLO 

2. 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 have created a greet function that takes a function as an argument.

# Python program to illustrate functions
# can be passed as arguments to other functions

def shout (text):

  return text.upper ()

  

def whisper (text):

return text.lower ()

 

def greet (func):

  # store the function in a variable

  greeting = func ( " Hi, I am created by a function passed as an argument. " )

  print greeting 

  
greet (shout)
greet (whisper)

Exit

 HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT. hi, i am created by a function passed as an argument. 

3. 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 the adder function.

 25 

This article courtesy of Mayank Agrawal . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.





# Python program to illustrate functions
# Functions can return another function

 

def create_adder (x):

def adder (y):

return x + y

 

return adder

 

add_15 = create_adder ( 15 )

 

print add_15 ( 10 )