Python is an object-oriented development language. The use of global variables in functions should generally be described as global variables. Only global variables that have been described in the function can be used.
The first thing to note is that you need to avoid using Python global variables as much as possible. Different modules can freely access global variables, which may cause unpredictability of global variables. For global variables, if programmer A modifies the value of _a, it may cause errors in the program. This kind of error is difficult to find and correct.
Global variables reduce the versatility between functions or modules, and different functions or modules depend on global variables. Similarly, global variables reduce the readability of the code, and readers may not know that a variable called is a global variable. But sometimes, Python global variables can solve problems that are difficult for local variables. Things must be divided into two.
There are two flexible usages of global variables in python:
gl.py:
gl_1 ='hello'
gl_2 ='world'
Use 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 +=1returnif __name__ =='__main__':modifyConstant()
print CONSTANT
1 Declaration method
Declare the Python global variable variable at the beginning of the file. When using the variable in a specific function, you need to declare the global variable in advance, otherwise the system treats the variable as a local variable. CONSTANT = 0 (Capitalize global variables for easy identification)
2 Modular approach
gl.py:
gl_1 ='hello'
gl_2 ='world'
Use 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 +=1returnif __name__ =='__main__':modifyConstant()
print CONSTANT
Content expansion:
What is a local variable
Popular definition: The variables defined inside the function are called local variables.
Not much to say, the code is as follows:
def test1():
a =300 #Define a local variable a,And initialize 300print("--test1--Before modification: a=%s"% a)
a =200 #Re-assign variable a to 200print("--test1--After modification: a=%s"% a)
def test2():
a =400 #Define another local variable a,And initialize 400print("--test2--After modification: a=%s"% a)
# Call function test1 separately,test2
test1()test2()
Output:
–Test1–Before modification: a=300
–Test1–After modification: a=200
–Test2–After modification: a=400
in conclusion:
So far, this article on how to understand global variables in Python is introduced. For more detailed explanations of global variables in Python, please search for ZaLou.Cn's previous articles or continue to browse related articles below. Hope you will support ZaLou more in the future. .Cn!
Recommended Posts