python variable domain global keyword

There are 4 types of Python variable scopes , namely:

L (Local) Local scope
E (Enclosing) In the function outside the closure function
G (Global) Global scope
B (Built-in) The built-in scope
is searched by the rule of L –> E –> G –> B , That is: if you can't find it locally, you will find it locally (such as a closure), if you can't find it, you will find it globally, and then you will find it in the built-in.

For the modification of global variables, if the global variable is int or str, if you want to modify the function variable in the function, you need to declare it as global in the function first, and then modify it. If it is a list or dict, you can directly modify

Note: Even if the variable has the same name, the local variable is preferentially referenced.

In the case of closures, if the internal function has no local variables, the environment variables of the closure will be referenced first
. For example, in the following figure: x = 5 is the environment variable of the closure, x = 4 is the local variable

Insert picture description here

When an internal function has a variable with the same name or a global variable that refers to an external function, and when this variable is modified, Python will think it is a local variable at this time, and the function does not have the definition and assignment of x, so an error is reported.
But after global x, no error will be reported. Finally, the global variable is also modified to x = 6

def func_c():
	global x
	x = x + 1
	print(x)

Reason: In the func_c function, x = x + 1 would first find the definition of x and the initial value of the assignment, but found that there is no in func_c(), so an error is reported if x is an undefined variable. But after declaring x as global, knowing that x is a global variable, that is, a variable that has been defined and declared, it can be added directly in this way. So go outside the func_c function to find x = 5 and substitute it in to get x = 6.
Finally, the global variable x is modified to 6.

Guess you like

Origin blog.csdn.net/angelsweet/article/details/114681611