Python function object

In Python, functions are considered as first class objects. It means we can use functions as perfect objects. In fact when we create a function, the Python interpreter internally creates an object. Since functions are objects, we can pass a function to another function just like we pass an object (or value) to a function. Also, it is possible to return a function from another function. This is similar to returning an object (or value) from a function.

The following possibilities are noteworthy:

  1. It is possible to assign a function to a variable.
  2. It is possible to define one function inside another function.
  3. It is possible to pass a function as parameter to another function.
  4. It is possible that a function can return another function.

function variable

A Python program to see how to assign a function to a variable.

CopiedCopy Code

def display(str): 
   return 'Hai '+str 
x = display("Krishna") 
print(x)

A Python program to know how to define a function inside another function.

CopiedCopy Code

def display(str): 
     def message(): 
        return 'How are U?' 
     result = message()+str 
     return result 
print(display("Krishna"))

A Python program to know how to pass a function as parameter to another function.

CopiedCopy Code

def display(fun): 
   return 'Hai '+ fun 
def message(): 
   return 'How are U? ' 
print(display(message()))

A Python program to know how a function can return another function.

CopiedCopy Code

def display(): 
   def message(): 
      return 'How are U?' 
   return message 
fun = display() 
print(fun())