Namespaces and scope of a function

Namespaces

   First, what is the name of the space python

  Name mapping objects. Namespace is a dictionary of realization, the key is the variable name, value is the value of the corresponding variable. Each namespace is not related to independence, a namespace can not have the same name, but different namespace can duplicate names without having any effect.

Popular talk: namespace is the name of the store where the three namespace (the remaining issues before the x = 1,1 stored in memory, that name x stored in the space where it is the name of the store with the name x 1 binding? local relations)
original link: https: //blog.csdn.net/lmseo5hy/article/details/80353099

 

  Second, the classification namespaces

  • Built-in namespace (Built-in)

   Storing the python built name, such as the name of the language, such as built-len, char, and some unusual names BaseException the like, can be called at any module, and with the start of the python interpreter generated close recovered, so it is the first name space is loaded.

>>> len
<built-in function len>
  • Global name space

   Name defined in the module, the module records the variables, including functions, classes, imported by other modules, the module-level variables and constants, with the execution file generated python

  • The local name space

   Name of the function defined in the record variable functions including parameters and local variables defined function, will produce only call the function, it will be recycled when the call is completed

>>> def func():
...     a = 1
...
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>>

 

  Third, the loading sequence namespace

         Built-in namespace (before running load) -> global namespace (program execution: from top to bottom loading) -> local namespace (program execution: when the call load)

 

  Fourth, namespace search order

          Local namespace -> global namespace -> Built-in namespace.

     When these three namespace also found, an exception will be thrown NameError

 

 

Scope of a function

Scope is a Python program can access the text area namespace directly.

In a python program, direct access to a variable, in turn access from the inside out until you find all of the scopes, otherwise undefined error will be reported.

  A the four scopes and search order

  • L (the Local) : innermost layer, comprising local variables, such as inside a function / method.
  • E (Enclosing) : contains non-local (non-local) is also non-global (non-global) variables. For example two nested function, a function (or class) A which also contains a function B, then B to A in the name is on the scope of nonlocal.
  • G (Free Join) : the outermost current script, such as global variables for the current module.
  • B (Built-in) : contains a built-in variable / keywords. The last to be searched

  Therefore, the search order is:  L -> E -> G -> B

Second, global and local variables   

  • Global variables: definitions have global scope outside the function, in the course of the entire file in there, anywhere can call (to create another class say)
  • Local variables: its only function is declared inside access, and global variables can be accessed throughout the program range. When you call a function, all variables declared within a function name will be added to the role
# ! / Usr / bin / the env Python 
# - * - Coding: UTF-. 8 - * - 
Total = 0   # This is a global variable 


DEF SUM (X, Y):
     # Returns the two parameters and. " 
    Total = X + Y   # Total here is a local variable. 
    Print ( " the function is a local variable: " , Total)
     return Total 


SUM ( . 1, 2 )
 Print ( " external function is a global variable: " , Total) 


"" " 
the function is local variables: 3 
outside the global variable is a function of: 0 
"" "
View Code

 

Three, global and nonlocal keyword

   When we want to change the variable outside the scope of the internal scope, you can use global and nonlocal keyword.

  • global Keywords: modify global variables 
# ! / Usr / bin / the env Python 
# - * - Coding: UTF-. 8 - * - 
Total = 0   # This is a global variable 


DEF SUM (X, Y):
     # Returns the two parameters and. " 
    Global Total 
    Total = X + Y   # Total here is a local variable. 
    Print ( " the function is a local variable: " , Total)
     return Total 


SUM ( . 1, 2 )
 Print ( " external function is a global variable: " , Total) 

"" " 
function the local variables: 3 
external functions are global variables: 3 
"" "
View Code
  • nonlocal keyword: Modify nested scopes (enclosing scope, the outer layer of the non-global scope), if the multi-layer nested functions, nonlocal will function from the current function on the level of the beginning of the layers to find, you know where to find the outermost layer, if not found, an exception is thrown
def func1():
    # 返回2个参数的和."
    a = 1
    print("start a : ", a)

    def func2():
        b = 2

        def func3():
            nonlocal a
            a = 3

        func3()

    func2()
    print("end a : ", a)

func1()

"""
start a :  1
end a :  3
"""
View Code

 

 Fourth, the local variable reference issues

a = 1
def test():
    a = a + 1
    print(a)


test()

"""
UnboundLocalError: local variable 'a' referenced before assignment
"""

       This is because the function of the internal variable assignment after modification, the variable will be regarded as Python interpreter local variable instead of the global variable, when the program execution time to a = a + 1, as this phrase is assigned to a , it became a local variable, then the execution return a (or print a) when, as a local variable has not been defined, they will naturally throw this error.

  This problem can be solved in the following ways:

   1. declared within a global a

 2. redefine a function inside a variable

 3. The transfer function parameters

 

Guess you like

Origin www.cnblogs.com/liangweijiang/p/11829545.html