Avoid using global variables whenever possible. Different modules can freely access global variables, which may lead to unpredictable global variables. For global variables, if programmer A modifies the value of _ A, programmer B also uses _ A, which may cause errors in the program. It is difficult to find and correct such errors.
Global variables reduce the universality between functions or modules. Different functions or modules depend on global variables. Similarly, global variables reduce code readability. Readers may not know that a variable called is a global variable.
However, in some cases, global variables can solve problems that are hard to solve by local variables. Things must be divided into two parts.
Global variables in Python have two flexible usage methods:
1 Statement
Declare the global variable at the beginning of the file,
When using this variable in a specific function, you must declare global variable in advance. Otherwise, the system regards this variable as a local variable.
Constant = 0
(Uppercase global variables for easy identification)
Def modifyconstant ():
Global constant
Print constant
Constant + = 1
Return
If _ name _ = '_ main __':
Modifyconstant ()
Print constant
2 module method (recommended)
Define global variables in a separate module:
# Gl. py
Gl_1 = 'hello'
Gl_2 = 'World'
Used 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 is suitable for sharing variables between different files. To some extent, it avoids the disadvantages of global variables mentioned at the beginning!