I recently wrote a python program and found a relatively trick place.
------------------------- A. py -------------------------
PWD = None
Def func1 ():
Global PWD
PWD = "pwd"
Print "PWD in func1 is:" + PWD
------------------------- B. py ------------------------
From a import *
Func1 ()
Print "PWD after call func1 () is:" + str (PWD)
The result of executing python B. py is as follows:
PWD in func1 is: pwd
PWD after call func1 () is: None
At the beginning, I thought that the value assigned to the global variable in the function cannot be passed back, that is
Global PWD only transmits the global variable to the local variable PWD, and then the user is operating on the local variable PWD, but this is not the case
The following example shows how to modify the import Statement.
------------------------- B. py ------------------------
Import
A. func1 ()
Print "PWD after call func1 () is:" + str (a. PWD)
Output
PWD in func1 is: pwd
PWD after call func1 () is: pwd
Therefore, I guess global can only change the global variables in this module (this py file ).
A. py adds a function.
------------------------- A. py ------------------------
PWD = None
Def func1 ():
Global PWD
PWD = "pwd"
Print "PWD in func1 is:" + PWD
Def func2 ():
Global PWD
Print "PWD in func2 is:" + PWD
------------------------- B. py ------------------------
From a import *
Print dir ()
Func1 ()
Func2 ()
The output result is
PWD in func1 is: pwd
PWD in func2 is: pwd
It seems that my conclusion is true:
Global can only change the global variables in this module (this py file ).
However, if the global variable is of the list or dict type, no problem occurs.
------------------------- A. py ------------------------
GLIST = ["glist"]
Def func1 ():
Global GLIST
GLIST [0] = "glist changed"
------------------------- B. py ------------------------
From a import *
Print GLIST [0]
Run python B. py to print
Glist changed
Conclusion:
It is best not to use "from a import *". Otherwise, you will find that you cannot assign values to simple global variables.