Python is an object-oriented development language. global variables are used in functions. global variables must be described, the following describes Python global variables.
Avoid using Python 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, 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 recommended modules)
, 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
- How to embed Python into C ++ applications?
- In-depth discussion of Ruby and Python syntax comparison
- Introduction to Python
- Python Learning Experience: version, IDE selection and encoding solution
- Analysis of Python GIL and thread security