1.函数作用域:
函数内部的局部变量只在函数内部生效;
全局变量可以在函数内部访问,但若试图在函数内部修改全局变量,则Python会创建一个同名的局部变量代替;
若一定要在函数内部修改全局变量的值,可以使用global关键字。
>>>var = 'Hello'
>>> def fun2():
global var
var = 'Baby'
print var
>>> fun2()
Baby
>>> print var
Baby
2.内嵌函数作用域:
python函数可以嵌套,但该内部函数除了其外部函数外,在外边或其它函数体都不能对其进行调用;
下面这样写会报错
def outside():
print ('I am outside!')
def inside():
print ('I am inside!')
inside()
正确的应该是:
def outside():
print ('I am outside!')
def inside():
print ('I am inside!')
inside()
outside()
执行结果:
I am outside!
I am inside!
在嵌套函数中,若希望在内部函数修改外部函数的局部变量,在python3中可以使用nonlocal关键字;
def outside():
var = 5
def inside():
nonlocal var
var *= var
return var
return inside()
>>>outside()
25
3.内嵌函数调用
不带参数内嵌函数:
访问inside()函数,写法一
def outside():
def inside():
print ('*******')
return inside()
直接调用outside()即可
写法二:
def outside():
def inside():
print ('*******')
return inside
需要用outside()()进行访问
------------------------------------
内嵌函数修改外部函数局部变量,python3写法:
def funX():
x = 5
def funY():
nonlocal x
x += 1
return x
return funY
a = funX()
print (a()) ->6
print (a()) ->7
python2写法:
def funX():
x = [5]
def funY():
x[0] += 1
return x[0]
a = funX()
print (a())
print (a())
带参数内嵌函数(闭包):
def funX(x):
def funY(y,z):
return x*y*z
return funY
print(funX(5)(8,2))
------------------------------------
def hellocounter(name):
count = [0]
def counter():
count[0] += 1 # nonlocal count
print 'Hello,'+name+','+str(count[0])+' access!'
return counter
hello = hellocounter('rita')
hello()
hello()
hello()
hellocounter('rita')()
hellocounter('rita')()
hellocounter('rita')()