# -*- coding: utf-8 -*-# return function # 1. function as return value # higher order functions can also return a function as a result value in addition to the function as a parameter Implement a variable parameter summation # Typically, the summation function is written def calc_sum (*args): ax = 0 for n in args: ax = ax + n return ax# can not return the result of a sum, but instead returns the sum of the function def lazy_sum (*args): def sum (): ax = 0 for n in args: ax = ax + n return ax return sum# when we call Lazy_sum (), the return is not the result of the summation, but the sum function f = lazy_sum (1, 3, 5, 7, 9) # output is the function sum itself print (f) # call Sumprint (f ()) # in this example , we also define the function s in the function lazy_sumUm, and the intrinsic function sum can refer to functions and local variables of the external function lazy_sum # when Lazy_sum returns the function sum, the relevant parameters and variables are stored in the returned function, a program called the "Closure (Closure)" has great power # A point to F1 = lazy_sum (1, 3, 5, 7, 9) f2 = lazy_sum (1, 3, 5, 7, 9) print (F1 == F2) # f1 == f2 false# f1 () and F2 () do not affect the results of the call # 2. Closure # Notice that the returned function references the variable args within its definition, so when a function returns a function, its internal local variables are also referenced by the new function # Another concern is that the returned function is not executed immediately, Instead, the Def count () is executed until F () is called (): fs = [] for i in range (1, 4): def f (): return i * i fs.append (f) return fsf1, f2, f3 = Count () # in the example above, each loop creates a new function and then returns the created 3 functions to the # result (9, 9, 9) print (F1 (),  F2 (), F3 ()) # The reason is that the returned function references the variable I, But it is not implemented immediately. When all 3 functions return, they refer to the variable i has become 3, so the final result is the 9# return function does not reference any loop variable, or the subsequent variable # a function can return a result of a calculation, you can also return a function # When returning a function, keep in mind that the function is not executed, and do not refer to any variables that may change in the return function
Python---return function