Functions that return function Python can not only return data types such as int, str, list, dict, but also return functions! For example, to define a function f (), we let it return a function g, which can be written like this:deff ():Print 'Call f () ...' #define function G: defg ():Print 'Call g () ...' #return function g: returnG look closely at the function definition above, and we define a function g inside the function f. Since the function g is also an object, the functions of the name G is the variable that points to the function g, so the outermost function f can return the variable g, which is the function G itself. Call the function f, and we'll get a function of the F return:>>> x = f ()#call F ()Call f () ...>>> x#the variable x is the function returned by F ():<function g at 0x1037bf320>>>> X ()#x points to the function, so you can callCall G () ...#calling X () is the code that executes the G () function definitionNote that the return function and return value are distinguished:defmyabs ():returnAbs#return functiondefMYABS2 (x):returnABS (x)#returns the result of a function call, which is a numeric valueThe return function can delay execution of some computations. For example, if you define a normal sum function:defcalc_sum (LST):returnwhen sum (LST) calls the Calc_sum () function, it is evaluated immediately and the result is obtained:>>> Calc_sum ([1, 2, 3, 4])10However, if you return a function, you can "defer calculation":defcalc_sum (LST):deflazy_sum ():returnsum (LST)returnLazy_sum#the call to Calc_sum () does not calculate the result, but instead returns the function:>>> f = calc_sum ([1, 2, 3, 4])>>>F<function Lazy_sum at 0x1037bfaa0>#The result is calculated when a call is made to the returned function:>>>f ()10since the function can be returned, we can decide in the subsequent code whether or not to invoke the function. Task Write a function Calc_prod (LST), which receives a list, returns a function, and returns a function that calculates the product of the parameter.
def Calc_prod (LST): def mul (): m=1; for inch lst: m*=i return m return= Calc _prod ([1, 2, 3, 4])print f ()
Python return function