Look at the code first:
Code One:
#!/usr/bin/python#coding:utf8x = def test ():p rint ' x= ', xtest ()
Code One execution Result:
x = 20
We have a slight modification on the basis of code one.
Code two:
x = def test ():p rint ' x= ', xx = 2 print ' Change X to ', Xtest ()
Code Two execution results:
X=traceback (most recent): file "D:\Demo\testGlobal.py", line to <module> test () file "D : \demo\testglobal.py ", line +, in test print ' x= ', xunboundlocalerror:local variable ' x ' referenced before assignmen T>>>
Parsing the problem: we tried to reassign X to 2 in line 4th, and because of the scope of the variable, the variable x in the function body and the variable x outside the function body are not considered to be the same variable, then the third row x is not assigned so it will be executed with an error.
Let's change the code two a little bit.
Code Three:
x = def test (): Global x print ' x= ', xx = 2 print ' Change X to ', Xtest ()
Code Three execution results:
x= 20change x to 2>>>
The execution results are in line with our expectations at this point.
Results analysis, when added to the Global keyword, the x variable is set as a global variable, that is, regardless of the function body or function outside the variable can be manipulated (modified), but the problem is the security of the variable, if more than one user of the variable to operate, The value of the last variable becomes unpredictable. Therefore, it is generally not recommended to use global variables.
The usage scenario for global variables typically occurs in multiple threads, where a thread begins to operate on a global variable, which is preceded by a mutex that can be manipulated by other threads after the thread has been released. This scenario will be described in detail in subsequent blogs.
Understanding of Python global variables (globals keyword)