关键词: python;作用域; Variable Scope;
1、Python中能够改变变量作用域的代码段是def、class、lamda三类。
代码块:if/elif/else、try/except/finally、for/while 等不更改变量的作用域,在其作用范围之外,仍然能够访问到变量。
2、Python变量搜索顺序是局部变量---上层变量---全局变量。
变量作用域
代码示例:
def scopetest():
localvar=6;
print(localvar)
scopetest()
#print(localvar) #去除注释这里会报错,因为localvar是本地变量
while True:
newvar=8
print(newvar)
break;
print(newvar)
try:
newlocal=7
raise Exception
except:
print(newlocal) #代码块外可以访问
Out:
6
8
8
7
number = 5
def func0():
#It's OK to reference.
print number
def func1():
#new local variable.
number = 10
print number
def func2():
#global declaration.
global number
print number
number = 10
print number
print "Before calling any function, number is {}".format(number)
print "Calling func0()----------"
func0()
print "Calling func1()----------"
func1()
print "After calling func1(), number is {}".format(number)
print "Calling func2()----------"
func2()
print "After calling func2(), number is {}".format(number)
Out:
Before calling any function, number is 5
Calling func0()----------
5
Calling func1()----------
10
After calling func1(), number is 5
Calling func2()----------
5
10
After calling func2(), number is 10
变量搜索顺序:
def scopetest():
var=6;
print(var)
def innerFunc():
print(var) #look here
innerFunc()
var=5
print(var)
scopetest()
print(var)
Out:
5
6
6
5
根据调用顺序反向搜索,先本地变量再全局变量,例如搜先在innerFunc中搜索本地变量,没有,向上一级scopetest,发现本地变量var=6,输出。