Python Function Objects
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:
- It is possible to assign a function to a variable.
- It is possible to define one function inside another function.
- It is possible to pass a function as parameter to another function.
- It is possible that a function can return another function.
A Python program to see how to assign a function to a variable.
def display(str): return 'Hai '+str x = display("Krishna") print(x)
A Python program to know how to define a function inside another function.
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.
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.
def display(): def message(): return 'How are U?' return message fun = display() print(fun())