Global variable Usage Analysis in python and python
This article analyzes the usage of global variables in python. Share it with you for your reference. The specific analysis is as follows:
Python is an object-oriented development language. global variables are used in functions. global variables must be described, here we will introduce Python global variables.
First, we should try to avoid using Python global variables. 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, errors may occur 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, Python 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:
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'def modifyConstant() : global CONSTANT print CONSTANT CONSTANT += 1 return if __name__ == '__main__' : modifyConstant() print CONSTANT
1 Statement
Declare the Python 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 are easy to recognize)
2 module method (recommended)
Recommended!
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'def modifyConstant() : global CONSTANT print CONSTANT CONSTANT += 1 return if __name__ == '__main__' : modifyConstant() print CONSTANT
I hope this article will help you with Python programming.