This part involves Python Knowledge of variable scope , Variable scope refers to the effective scope of a variable , Direct understanding is Python Variables in are not accessible anywhere , There are restrictions .
In general, the scope of a variable is Block level 、 function 、 class 、 modular 、 Bag, etc , The level is from childhood to .Python There is no block level scope in , So when we write code , The following code is correct .
if True: x = "hello world" # Because there is no block level scope , so if Variables in the code block x Can be accessed from outside print(x)
stay Python Common block level scopes in are if sentence 、for sentence 、while sentence 、with Context statement .
As mentioned above, the scope is Python A program can directly access the scope of a variable ,Python There are a total of 4 Kind of , They are as follows :
A classic case is as follows :
# Built in scope Built-in x = int(5/2) # Global scope Global global_var = 0 def outer(): # In a function other than a closure function Enclosing out_var = 1 def inner(): # Local scope Local inner_var = 2
stay Python The order of finding variables in is from inside to outside , First, local , And then outside , In the global , Built in , This rule is called LEGB The rules
.
Make the following study more interesting , You can study how variables change in the following code .
len = len([]) def a(): len = 1 def b(): len = 2 print(len) b() a()
It's defined in Internal function The variable of has a local scope , It's defined in Function external Variables of have global scope .
Local variables can only be accessed inside the function they are declared , Global variables can be accessed throughout the program .
# Global variables x = 0 def demo(): # At this time x It's a local variable x = 123 print(" Function is a local variable x = ", x) demo() print(" Outside the function is the global variable x= ", x)
Output results , Inside the function is 123
, The outside of the function is still 0
.
If you want the function to be internal ( Internal scope ) You can modify variables in an external scope , Need to use global
keyword .
# Global variables x = 0 def demo(): # At this time x Global variable global x x = 123 print(" Function is a local variable x = ", x) demo() print(" Outside the function is the global variable x= ", x)
At this point, the output is 123
了 , There's one more thing to note , In the function content, if you want to modify the value of the global variable ,global
Keywords must be written before variable operations .
def demo(): # At this time x Global variable x = 123 global x print(" Function is a local variable x = ", x)
The code has syntax errors :
SyntaxError: name 'x' is assigned to before global declaration
In addition to the above knowledge , Remember to use a variable inside a function , Without changing the value , No statement , By default, the value of global variable is obtained .
x = " Global variables " def demo(): print(x) demo()
There is also a real interview question in the global variable , Often appear , May I ask the following code running results .
x = 10 def demo(): x += 1 print(x) demo()
The conclusion is to report an error , The reason is that demo Function runtime , It will be calculated first. x+1
, Variables need to be declared and assigned before they are evaluated , But the inner part of the function is right x
No initialization operation , So report a mistake .
If you want to modify the nested scope (Enclosing Scope ) The variables in the , need nonlocal
keyword , The test code is as follows :
def outer(): num = 10 def inner(): # nonlocal keyword nonlocal num num = 100 print(num) inner() print(num) outer()
The output is self tested , Be careful nonlocal
Keyword must be Python3.X+ edition ,Python 2.X There will be syntax errors in the version :
nonlocal num ^ SyntaxError: invalid syntax`
nonlocal
Can not replace global
, For example, the following code , Comment out the variable declaration of the outer function , This will bring up SyntaxError: no binding for nonlocal 'num' found
error .
num = 10 def outer(): # Comment out the line # num = 10 def inner(): # nonlocal keyword nonlocal num num = 100 print(num) inner() print(num) outer()
In multiple nesting ,nonlocal
It only goes up one level , If the upper floor doesn't have , Will continue to go up , You can comment the following code separately to see the result .
num = 10 def outer(): num = 100 def inner(): num = 1000 def inner1(): nonlocal num num = 10000 print(num) inner1() print(num) inner() print(num) outer()
What are the local variables and global variables , Can pass locals()
and globals()
Two built-in functions get .
x = " Global variables " def demo(): y = " local variable " print(locals()) print(x) demo() print(globals()) print(locals())
This blog explains Python Scope of action , And right global and nonlocal Keywords learned , I hope it helped you .