The basic usage of these two keywords is outlined in the previous article:
Global is used for local modification or redefinition of globals
Nonlocal used to modify or redefine external variables (except global variables) in an internal scope
It's just a shallow way of understanding.
Note the characteristics of Python, the variables are mutable and immutable, for the mutable variable, in the internal scope of the changes can be done completely, do not need the above two keyword modification, such as the following program:
A = 12
Li = [1, 2, 3]
def g ():
b = 11
LI[2] = 4 #li变量在内部作用域内被修改了
def func ():
Print (a)
Print (b)
Func ()
Return
if __name__ = = ' __main__ ':
G ()
Print (LI)
But in doing so, the situation has changed:
A = 12
Li = [1, 2, 3]
def g ():
b = 11
Li = [1, 1, 1] #这时修改的是整个list, which is equivalent to a variable redefinition, so Li is considered local and does not affect global variables
def func ():
Print (a)
Print (b)
Func ()
Return
if __name__ = = ' __main__ ':
G ()
Print (LI)
In conjunction with Python's knowledge of memory management, we can understand that all operations within, nested scopes are possible, as long as the reallocation of variable memory is not involved (such as immutable variable assignment, mutable variable overall assignment). If you want to use the same name to point to another piece of memory, be particularly clear about whether the change is global or local
Python Global vs nonlocal (2)