First, the name space
definition : Name-to-object mapping. A namespace is an implementation of a dictionary, a key is a variable name, and a value is a value that corresponds to a variable. The namespaces are independent of each other and cannot have names in a namespace, but different namespaces can have duplicate names without any effect.
Classification:
1. Global namespace:
The namespace that is created when code is run.
2. Local namespaces:
A temporary space, such as a function, that is opened during a program's operation.
3. Built-in namespaces:
Open space for storing commonly used built-in methods, such as input,print,str,list, which are variables of the built-in namespaces before the program runs the load code
Plus loading sequence: load Order: Built-in namespaces (pre-Program load)-Global namespaces (program run: Load from top to bottom) local namespaces (program run: Load only when called) Order of values: In the local call: Local namespace, global namespace, built-in namespaces, Global Call: Built-in namespaces, global namespaces
Second, scope
Global scope: Contains built-in namespaces, global namespaces , can be referenced anywhere throughout the file, are globally valid
Local scope: Local namespace, only valid locally
Global keyword, nonlocal keyword.
Global
1, declare a global variable.
2, Global (limited to string, number) is required when local scope wants to make a modification to a globally scoped global variable.
Nonlocal:
1, global variables cannot be modified.
2, in the local scope, the variables of the parent scope (or the outer scope non-global scope) are referenced and modified, and which layer of the reference, from that layer and the following this variable all changed.
Python Namespaces and Scopes