This example analyzes the use of global variables in Python. Share to everyone for your reference. The specific analysis is as follows:
Python is an object-oriented development language, the use of global variables in functions, generally should be described as a global variable, only in the function of the described global variables can be used, here to introduce the next Python global variables related issues.
The first thing you should say is that you need to avoid using Python global variables as much as possible. 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:
gl.py:
1 2 |
Gl_1 = ' Hello ' gl_2 = ' world ' |
Use in other modules
a.py:
1 2 3 |
Import GL def hello_world () print Gl.gl_1, gl.gl_2 |
b.py:
1 2 3 4 5 6 7 8 9 10 11-12 |
Import GL def fun1 () gl.gl_1 = ' Hello ' gl.gl_2 = ' world ' def modifyconstant (): Global CONSTANT print CONSTANT CONSTANT = 1 return if __name__ = = ' __main__ ': modifyconstant () 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!
gl.py:
1 2 |
Gl_1 = ' Hello ' gl_2 = ' world ' |
Use in other modules
a.py:
1 2 3 |
Import GL def hello_world () print Gl.gl_1, gl.gl_2 |
b.py:
1 2 3 4 5 6 7 8 9 10 11-12 |
Import GL def fun1 () gl.gl_1 = ' Hello ' gl.gl_2 = ' world ' def modifyconstant (): Global CONSTANT print CONSTANT CONSTANT = 1 return if __name__ = = ' __main__ ': modifyconstant () print CONSTANT |