Python is an object-oriented development language, the use of global variables in functions, generally should be described as global variables, only in the function of the described global variables can be used, the following describes the Python global variables related issues.
You should try to avoid using Python global variables. Different modules are free to access global variables, which can lead to the unpredictability of global variables. For global variables, if programmer a modifies the value of _a, this 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 are dependent on global variables. Similarly, a global variable reduces the readability of the code, and the reader may not know that one of the variables invoked is a global variable. But at some point, Python global variables can solve problems that are difficult for local variables to solve. Things to be in Split. There are two flexible ways to use global variables in Python:
1. #gl. py
2. Gl_1 = ' Hello '
3. gl_2 = ' World '
4.
5. Use in other modules
6. #a. py
7. Import GL
8.
9. Def hello_world ()
Print Gl.gl_1, gl.gl_2
11.
#b. py
Import GL
14.
def fun1 ()
Gl.gl_1 = ' Hello '
gl.gl_2 = ' World '
Def modifyconstant ():
Global CONSTANT
Print CONSTANT
CONSTANT + 1
Return
23.
if __name__ = = ' __main__ ':
Modifyconstant ()
Num. Print CONSTANT
1 Declaration Law
The python global variable variable is declared at the beginning of the file, and the global variable is required in advance when the variable is used in a specific function, otherwise the system treats the variable as a local variable. CONSTANT = 0 (Capitalize global variables for easy identification)
2 Modular Method (recommended)
Recommended.
1. #gl. py
2. Gl_1 = ' Hello '
3. gl_2 = ' World '
4.
5. Use in other modules
6. #a. py
7. Import GL
8.
9. Def hello_world ()
Print Gl.gl_1, gl.gl_2
11.
#b. py
Import GL
14.
def fun1 ()
Gl.gl_1 = ' Hello '
gl.gl_2 = ' World '
Def modifyconstant ():
Global CONSTANT
Print CONSTANT
CONSTANT + 1
Return
23.
if __name__ = = ' __main__ ':
Modifyconstant ()
Num. Print CONSTANT