You should try to avoid using global variables. Different modules are free to access global variables, which can lead to unpredictable global variables. For global variables, if programmer a modifies the value of _a, programmer B also uses _a, which can cause errors in the program. Such errors are difficult to detect and correct.
Global variables reduce the commonality between functions or modules, and different functions or modules depend on global variables. Similarly, global variables reduce the readability of the code, and the reader may not know that a variable being called is a global variable.
But at some point, global variables can solve problems that are difficult to solve with local variables. Things must be divided into divided.
There are two kinds of flexible uses of global variables in Python:
1 Declaration Law
Declare the global variable variable at the beginning of the file,
When you use this variable in a specific function, you need to declare the global variable beforehand, otherwise the system treats the variable as a local variable.
CONSTANT = 0 (capitalize the global variable for easy identification)
Def modifyconstant ():
Global CONSTANT
Print CONSTANT
CONSTANT + = 1
Return
if __name__ = = ' __main__ ':
Modifyconstant ()
Print CONSTANT
2 Module method (recommended)
Define the global variables in a separate module:
#gl. py
Gl_1 = ' Hello '
gl_2 = ' World '
Use in other modules
#a. py
Import GL
def Hello_world ()
Print Gl.gl_1, gl.gl_2
#b. py
Import GL
def fun1 ()
Gl.gl_1 = ' Hello '
gl.gl_2 = ' World '
The second method, which is applicable to the sharing of variables between different files, and to some extent avoids the drawbacks of the global variables mentioned at the beginning, recommend!
Go: Python's global variables