First, the name space
1, definition: aka Name space, as the name implies, is the place to store the name. For example: if the variable x = the store in memory,
2, Category:
locals: namespaces within functions, including local variables and formal parameters
globals: global variable
Builtins: namespaces for built-in modules
Note: The scope of the different variables is determined by the namespace in which the variable resides.
3, scope (scope)
global scope: Globally valid
local scope: locally valid
To view the scope method: Globals (), locals ()
4. Scope Lookup Order: LEGB
L:locals is a namespace within a function
E:enclosing (enclosing) is the namespace of the outer nested function
G:globals Global Variables
B:builtins the namespace of the built-in module
Instance:
Age = 20deffunc1 (): Age= 18Print('func1:', age)#func1:18 defFunc2 (): Age= 28Print('Func2:', age)#func2:28 deffunc3 ():Print('func3:', age)#func3:28func3 () Func2 () func1 ( )Print('Global:', age)#Global:
Second, function closure
1. Definition:
Closures are function definitions and function expressions in the function body of another function (nested functions). Furthermore, these intrinsic functions can access
All local variables, parameters declared in the outer function in which they reside, when one such intrinsic function is outside the outer function containing them
when called, a closure is formed. that is, the intrinsic function is executed after the external function returns. And when this inner function executes, it
It is still necessary to access local variables, parameters, and other intrinsic functions of its external functions. These local variables, arguments, and function declarations (initially)
Is the value of the external function when it returns, but it is also affected by the intrinsic function.
2, the meaning of closure:
Returns the Function object. is not just a function object, but also wraps a layer of scope outside the inner function, which makes the function no matter
Where to call, take precedence over the scope of your own outer envelope.
3. Example:
1 #! /usr/bin/env Python32 #-*-coding:utf-8-*-3 4 defouter ():5Name ='SC'6 definner ():7 Print('to print variables for external functions within inner', name)8 returnInner9f =outer () # After the outer function call, the return value is inner, then f = InnerTen f () # At this time, f () = inner () One A #4 rows to 10 lines is a complete closure process
Python Namespaces and closures