louyaoluan 发表于 2017-4-23 10:34:02

Python作用域(转)

python 变量作用域
分类: Python 2011-07-23 11:20 1143人阅读 评论(1) 收藏 举报
原地址:http://blog.csdn.net/lovingprince/article/details/6627555
目录(?)[+]
几个概念:
python能够改变变量作用域的代码段是def、class、lamda.
if/elif/else、try/except/finally、for/while 并不能涉及变量作用域的更改,也就是说他们的代码块中的变量,在外部也是可以访问的
变量搜索路径是:本地变量->全局变量

python能够改变变量作用域的代码段是def、class、lamda.
view plaincopyprint?
def scopetest():
localvar=6;
print(localvar)
scopetest()
#print(localvar) #去除注释这里会报错,因为localvar是本地变量
if/elif/else、try/except/finally、for/while
view plaincopyprint?
while True:
newvar=8
print(newvar)
break;
print(newvar)
try:
newlocal=7
raise Exception
except:
print(newlocal)#可以直接使用哦
输出结果:8 8 7
可见这个关键字中定义变量,他们的作用域跟外部是一致的,这个跟Java的作用域概念有点不一样。
变量搜索路径是:本地变量->全局变量
view plaincopyprint?
def scopetest():
var=6;
print(var)#
var=5   
print(var)
scopetest()
print(var)
输出结果:5 6 5
这里var 首先搜索的是本地变量,scopetest()中 var=6相当于自己定义了一个局部变量,赋值为6. 当然如果的确要修改全局变量的值,则需要如下:
view plaincopyprint?
def scopetest():
global var   
var=6;
print(var)#
var=5   
print(var)
scopetest()
print(var)
输出结果:5 6 6
再看一种这种情况:
view plaincopyprint?
def scopetest():
var=6;
print(var)#
def innerFunc():
print(var)#look here
innerFunc()
var=5   
print(var)
scopetest()
print(var)
输出结果:5 6 6 5
根据调用顺序反向搜索,先本地变量再全局变量,例如搜先在innerFunc中搜索本地变量,没有,好吧,找找调用关系上一级scopetest,发现本地变量var=6,OK,就用他了。
页: [1]
查看完整版本: Python作用域(转)