Python closure: return function usage example, python example
Closure is nothing terrible. If they are correct, they can be very powerful. A closure is a function dynamically generated and returned by other functions. In general, there is also an "inner" function within a function. This "inner" function is returned, it can access the variables in the local namespace of its creator.
The following is a simple example:
# Define a function def make_closure (a): # define another function in the function. In fact, the function in this function is considered as the closure def closure (): # print the passed number. print ('I know the secret: % d' % a) return closure # assign a value to the make_closure function, the 7 parameter is to give the parameter aclosure1 = make_closure (7) # This is actually to call the returned closure function, and then execute the closure function closure1 ()
Running result:
In my understanding, closure is actually another function B in function A, because the return value is function B, so when calling function A, If you want function B to be executed as well, you must call callback function B again.
If N functions are embedded in a function, it needs to be initialized N times.
You may wonder what the purpose is. In practice, you can compile very general functions with a large number of options, and then group the functions that are simpler and more specialized.
In the following example, a string Formatting Function is created:
Def format_and_pad (template, space): def formatter (x): return (template % x ). must ust (space) return formatter # create a floating-point formatter fmt = format_and_pad ('%. 4f ', 15) fmt (1.756)
Running result:
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.