The following code has two functions as follows
def f2(c, d): return c, d def f1(a, b): c = a + 1 d = b + 2
How can this code be re-worked to make one function return another function?
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.
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)
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy. Accept Learn more