def ex5():
var = 'foo'
def inner():
global var
var = 'bar'
print ('inside inner, var is ', var)
inner()
print ('inside outer function, var is ', var)
ex5()
print ("In global view, var is :",var)
執行結果:-----------------------------------------
inside inner, var is bar
inside outer function, var is foo
In global view, var is : bar
#用function修改nonlocal var的技巧
def ex5():
var = 'foo'
def inner():
global var
var = 'bar'
print ('inside inner, var is ', var)
inner()
print ('inside outer function, var is ', var)
ex5()
print ("In global view, var is :",var)
執行結果:-----------------
inside inner, var is bar
inside outer function, var is bar #由此行可知outer function中的值被修改為bar
Traceback (most recent call last):
File "C:/Python32/setOuter.py", line 13, in <module>
print ("In global view, var is :",var)
NameError: name 'var' is not defined
沒有留言:
張貼留言