How can a Python function return a function?

PythonServer Side ProgrammingProgramming

Python supports first-class functions. In fact, all functions in python are first-class functions.

Python may return functions from functions, store functions in collections such as lists and generally treat them as you would any variable or object.

Defining functions in other functions and returning functions are all possible.

The given code is re-worked as follows. We define functions inside functions and return these.

Example

def f2(c, d):
    return c, d
def f1(a, b):
    c = a + 1
    d = b + 2
    return lambda: f2(c,d)
result = f1(1, 2)
print result
print result()

Output

C:/Users/TutorialsPoint1/~.py
<function <lambda> at 0x0000000003041CF8>
(2, 4)
raja
Published on 07-Dec-2017 10:28:23
Advertisements