python namespace

Namespaces

After the python interpreter starts executing, it will open up a space in memory, whenever it encounters a variable, put the variable relationship between the name and the value recorded, but when faced with the function definition, the interpreter just the function name is read into memory, indicating that the function exists, as to the internal logic of variables and functions, the interpreter is not concerned about. that is the beginning of time function just loaded in, nothing more, and only when the function is called time of the visit, the interpreter will open up space for internal variables according to the variables declared within a function. with the function completes, the function of the internal variables as a function of the space occupied will be emptied finished.

def fun():   
    a = 10   
    print(a)
fun()
print(a)    # a不存在了已经..

We give the name of the relationship between storage space and value from a name: namespace we are variables in memory is stored in this space.

Namespace Category:

  1. Global namespace -> py us directly in the document, the variable declared outside the function belong to the global namespace

  2. Local namespace -> variables declared in a function will be kept in the local namespace

  3. Built-in namespace -> storage python interpreter provides us with the name, list, tuple, str, int these are built namespaces  

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

a = 10
def func():  
    a = 20   
    print(a)

func()  # 20

Scope: scope is the scope, in accordance with the entry into force of the range of view into global scope and local scope

   Global scope: includes built-namespace and global namespace anywhere in the entire file can be used (follow from top to bottom by ⾏ execution).

   The local scope: internal function may be used.

Using the domain namespace for:

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

We can see by the global globals () function for Use with domain content, it can be viewed as a local variable amount Use and function with domain information by locals ()

a = 10
def func():   
    a = 40   
    b = 20   
    print("哈哈")   
    print(a, b)        
    print(globals())    # 打印全局作用域中的内容   
    print(locals())     # 打印当前作用域中的内容
func()

img

  • Namespace Category

    命名空间分类:
    1. 全局命名空间--> 我们直接在py文件中, 函数外声明的变量都属于全局命名空间
    2. 局部命名空间--> 在函数中声明的变量会放在局部命名空间
    3. 内置命名空间--> 存放python解释器为我们提供的名字, list, tuple, str, int这些都是内置命名空间 
  • Load order

    #内置空间>全局空间>局部空间
  • The value of the order

    #局部空间>全局空间>内置空间
  • Scope

    #全局作用域:
      内置空间+全局空间
    #局部作用域
      局部空间

Guess you like

Origin www.cnblogs.com/luckinlee/p/11620074.html