04: In Python functions are objects tutorial

Q. Are functions objects in Python?
A. Yes. In Python, a function is an object of type function. A function being an object means it is possible to pass a function object around as argument or as return value or to assign another name to the function object. Closures are possible in Python because functions are first-class objects.

Q. What is a higher-order function?
A. In mathematics and computer science, a higher-order function is a function that does at least one of the following:

1) takes one or more functions as arguments

2) returns a function as its result.

Functions as arguments

You can pass functions as one of the arguments to another function.

Having a function as a return value

Assigning a function to a variable

As you can see that the function “hi” is assigned to a variable “greet”. The “hi” function is deleted, and “greet” can be invoked.

Python inner (aka nested) functions

Q. What are they good for?
A. It is used for encapsulation. You use inner functions to protect them from everything happening outside of the function, meaning that they are hidden from the global scope.

Inner functions are useful in 1) Closures 2) Factory functions.

Here is another example where inner function is used:

Python Closures

A closure is a way of keeping alive a variable even when the function has returned. So, in a closure, a function is defined along with the environment. In Python, this is done by nesting a function inside the encapsulating function and then returning the underlying function.

Python factory function

Factory Method is a creational design pattern used to create concrete implementations of a common interface.


800+ Java & Big Data Interview Q&As

Top