python notice7 functions and nested namespace

A namespace

  After the python interpreter starts executing, it will open up a space in memory, whenever it encounters a variable, the variable will be the relationship between the name and the value recorded, but when faced with the function definition, the interpreter first the function name is read into memory, regardless of the internal variables and logic functions. When the function is called and visited, the interpreter will be based on the variables declared inside a function to open up the internal space variables, with the function completes, the function of the internal variables as a function of the space occupied will be finished and released.

  Namespace: storage space for the names and values ​​of variables.

Namespace Category:

  1. global namespace: py file directly, the variable declared outside the function belong to the global namespace.  

  2. Local namespaces: variables declared in a function will be kept in the local namespace.

  3. Built Namespace: storing python interpreter inner space of the functions or variables.

Load order:

  1. Built-in namespace.

  2. global namespace.

  3. Local namespace. (When the function is executed)

The value of the order:

  1. local namespace.

  2. global namespace.

  3. Built-in namespace.

Second, the scope: scope

  1. The global scope: global name space + built-namespace

  2. Local scope: local namespace

  By Globals () function to view the contents of the global scope; by about locals () function to see the information variables and functions local scope.

= 10 A
 DEF FUNC (): 
    A = 40 
    B = 20 is
     Print (Globals ()) # print for Use with the global domain content 
    Print (about locals ()) # print Use for topical use domain content 
FUNC ()

Third, the nested functions

  Defined functions inside the function and call.

# Nested functions 
DEF fun1 ():
     Print (222 )
     DEF fun2 ():
         Print (666 )
     Print (444 ) 
    fun2 () 
    Print (888 )
 Print (333 ) 
fun1 () 
Print (555)

Use the keyword global and nonlocal:

  global: global variables inside a function is introduced, and can modify global variables.

  nonlocal: internal function, the inner layer functions to access local variables in the function, can also modify it.

= 100 A
 DEF FUNC ():
     Global A      # introduced with global variables A 
    A = 28       # modify global variables A                  
    Print (A)      # 28 
FUNC ()
 Print (A)     # 28
A = 10
 DEF func1 (): 
    A = 20 is
     DEF func2 (): 
        nonlocal A     # incorporated parent function variable 
        A = 30          # modify the parent function variables 
        Print (A) 
    func2 () 
Print (A)     # 10 
func1 ()     # 30           

 

Guess you like

Origin www.cnblogs.com/xiaolu-fan/p/11230270.html