preface
Recently, when I was answering questions in the group, I often encountered errors in the use of variables, indents, parameters and other aspects, resulting in the failure of the program.
Today, I'm going to write an article by myself.
Python variable scope, and lifecycle.
Thoroughly understand how variables should be used.
Knowledge points
The use of variables is different in scope and life cycle.
1. Variable scope
local variable
The code snippets that python can affect the scope of variables are def, class and lamda.
def scopeTest(): localValur = 6 print(localValur) scopeTest() # print(localValur) #If you remove the comment, an error will be reported here because localValur is a local variable
Output results:
6
Results of removing comments:
6 Traceback (most recent call last): File "D:\PythonDemo\test--\cycleTest.py", line 6, in <module> print(localValur) #If you remove the comment, an error will be reported here because localValur is a local variable NameError: name 'localValur' is not defined
if/elif/else, try/except/finally and for/while cannot involve the change of variable scope, that is, the variables in their code block can also be accessed externally.
for i in range(3): localValur=i+1 pass print(i) print(localValur)
Output results:
2 3
The variable search path is: local variable - > global variable.
def scopeTest(): var = 6 print(var) # def innerFunc(): print(f"var:{var}") #Pay attention here innerFunc() var = 5 print(var) scopeTest() print(var)
Output results:
5 6 var:6 5
Summary of local variables:
① The variables in the def function cannot be shared with the variables in the file
② Def functions can be nested, and internal def functions can use variables of external def functions.
Global variable global keyword
We define a variable outside the file. Is there no way to operate through the function?
value=100 def scopeTest(): # global value value +=1 print(value) scopeTest() print(value)
When no declaration is made, the output results are as follows:
100 Traceback (most recent call last): File "D:\PythonDemo\test--\cycleTest.py", line 8, in <module> scopeTest() File "D:\PythonDemo\test--\cycleTest.py", line 5, in scopeTest value +=1 UnboundLocalError: local variable 'value' referenced before assignment
Remove comments:
value=100 def scopeTest(): global value value +=1 print(value) scopeTest() print(value)
At this time, the modified result in the function will also affect the file. The output result is:
100 101
Variable life cycle
1. The variables in the def function become invalid after the function ends.
2. class, life cycle of variable
Let's look at the case first:
Create a class, and then change the index value in the class to an ordered value
class classTest: index=0 arr=[] add=classTest for i in range(5): add.index=i arr.append(add) for cc in arr: print(cc.index)
Output results:
4 4 4 4 4
Why does the result turn into 4? Because the data type of the variable add here is a type class.
print(type(add))
<class 'type'>
The value in the array changes with the 'type' object. The life cycle of add has not changed since it was declared.
Correct writing:
class classTest: index=0 for i in range(5): add = classTest() print(type(add)) add.index=i arr.append(add) for cc in arr: print(cc.index)
Display results:
<class '__main__.classTest'> <class '__main__.classTest'> <class '__main__.classTest'> <class '__main__.classTest'> <class '__main__.classTest'> 0 1 2 3 4
At this time, our result is correct. The life cycle of add is a new variable every time it is created.
epilogue
Although there are few knowledge points, its importance is irreplaceable. Many seemingly unsolvable mistakes can be solved by relying on basic knowledge.
Many bloggers are recommending the use of functions, and I emphasize basic training.
Recommend a book to ensure that the foundation does not fall behind.
Link: https://pan.baidu.com/s/1YllgwFf3aMbZLHeNyoLkUQ
Extraction code: 9vwh