http://blog.csdn.net/lovingprince/article/details/6627555
Several concepts:
- The code snippet in which Python can change the scope of a variable is Def, class, Lamda.
- If/elif/else, try/except/finally, For/while are not involved in variable scope changes, which means that the variables in their code block are also accessible externally.
- Variable search path is: local variable, global variable
- The code snippet in which Python can change the scope of a variable is Def, class, Lamda.
[Python]View Plaincopyprint?
- Def scopetest ():
- localvar=6;
- print (Localvar)
- Scopetest ()
- #print (Localvar) #去除注释这里会报错 because Localvar is a local variable
- If/elif/else, try/except/finally, For/while
[Python]View Plaincopyprint?
- while true:
- newvar=8  
- print (newvar)
- break;
-   
- span class= "keyword" >print (newvar)
-   
- TRY:  
- newlocal=7  
- RAISE EXCEPTION  
- EXCEPT:  
- print (newlocal) #可以直接使用哦
Output results: 8 8 7
It is visible that the variables are defined in this keyword, and their scope is consistent with the outside, which is a bit different from the concept of Java scope.
- Variable search path is: local variable, global variable
[Python]View Plaincopyprint?
- Def scopetest ():
- var=6;
- Print (Var)#
- var=5
- Print (VAR)
- Scopetest ()
- Print (VAR)
Output results: 5 6 5
Here Var first searches for local variables, and scopetest () var=6 the equivalent of defining a local variable, assigned a value of 6. Of course if you really want to modify the value of a global variable, you need the following:
[Python]View Plaincopyprint?
- Def scopetest ():
- Global Var
- var=6;
- Print (Var)#
- var=5
- Print (VAR)
- Scopetest ()
- Print (VAR)
Output results: 5 6 6
Let's look at one such situation:
[Python]View Plaincopyprint?
- def scopetest ():
- var=6;  
- print (var) #
- def innerfunc ():
- print (var) #look here
- innerfunc ()
-       
- Var=5   
- print (var)
- scopetest ()
- print (var)
Output results: 5 6 6 5
Reverse search According to the order of the call, first local variables and global variables, such as search for local variables in Innerfunc, no, OK, find the call relationship on the first level scopetest, found the local variable Var=6,ok, use him.
Python variable scope