Http://www.cnblogs.com/phoebus0501/archive/2011/01/18/1938728.html
You should try to avoid using global variables because:
1) 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.
2) 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.
Use of global variables in Python:
1 Declaration Law
1) Declare the global variable at the beginning of the file: VAR = 0 (capitalize the global variable for easy identification)
2) When using the variable in a specific function, you need to declare the global VAR beforehand, otherwise the system treats the variable as a local variable.
VAR = Ten #声明全局变量
Def get_var ():
Global VAR #声明变量为global
Print VAR,
VAR + = 1
if __name__ = = ' __main__ ':
For I in range (5):
Get_var ()
#Result:
# 10 11 12 13 14
2 Module method (recommended)
1) Define the global variables in a separate module:
#global. py
Global_1 = 1
Global_2 = 2
Global_3 = ' Hello world '
2) Then import the global variable definition module in another module and use the global variable in the new module:
Import Globalvalues
Def printglobal ():
Print (Globalvalues.global_1)
Print (Globalvalues.global_3)
Globalvalues.global_2 + = 1 # Modify values
if __name__ = = ' __main__ ':
Printglobal ()
Print (globalvalues.global_2)
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!
Python's global variables