Python的内嵌函数和闭介绍
1.内嵌函数:在函数中定义函数
内嵌函数例子1、
# 代码段1
def fun1():
print('外层函数正在被调用')
def fun2():
print('内层函数正在被调用')
fun1()
'''输出如下:
外层函数正在被调用
'''
内嵌函数例子2:
# 代码段2
def fun1():
print('外层函数正在被调用')
def fun2():
print('内层函数正在被调用')
fun2()
fun1()
'''输出:
外层函数正在被调用
内层函数正在被调用
'''
'''
fun2() # 内嵌函数不能直接被调用,否则会报如下错误
NameError: name 'fun2' is not defined
'''
注:①内嵌函数不能再外层函数被调用的过程中自动被调用
②内部函数不能被外部直接使用,需要通过其外层函数的调用发挥作用
2.闭包定义和例子
闭包: 出现在嵌套函数中,指的是内层函数引用到了外层函数的变量,就形成了闭包。
内嵌函数例子一:
# 代码段3
def funx(x):
def funy(y):
return x * y
return funy # 返回内层函数
print funx(2)(5) # 对闭包的调用
'''输出:
10
'''
m = funx(2) # 只对外层函数进行了调用
print type(m) # 所以函数的返回类型及m的类型为function
'''输出:
<type 'function'>
'''
print m(3) # 继续对内层函数进行调用
'''输出:
6
'''
3.在函数内部修改全局变量的值:global关键字
注:能不直接访问全局变量尽量不要访问,如需使用全局变量可以使用函数进行传参。
num = 3
def count():
global num
num = 5
print(num)
count()
'''输出:
5
'''
print num
'''输出:
5
'''
4.在内嵌函数中修改外部函数的局部变量
因为nonlocal是在Python3.x中新增的关键字,python2.x不提供支持,
文中提出在Python2.x解决嵌套函数引用外部变量的方法只有使用global 关键字定义全局变量,
另一种可行的解决方案是使用列表或字典代替要操作的关键字。
1).python3.x 使用nonlocal关键字
2).python2.x 借助list或dict实现
例子一:python3.x 使用nonlocal关键字
# 1).python3.x 使用nonlocal关键字
def outer():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
'''
inner: 2
outer: 2
'''
例子二:python2.x 借助list或dict实现
# 2).python2.x 借助list或dict实现
def outer():
x = [1]
def inner():
x[0] += 1 # 修改x[0]保存的值
print "inner:", x[0]
inner()
print "outer:", x[0]
outer()
'''
inner: 2
outer: 2
'''
例子三:以下是闭包的两个例子
# 例子1:
def funX():
x = 5
def funY():
nonlocal x
x += 1
return x
return funY
a = funX()
print(a())
print(a())
print(a())
'''
#例子1结果:
6
7
8
'''
# 例子2:
def funX():
x = 5
def funY():
nonlocal x
x += 1
return x
return funY
a = funX()
print(a())
a = funX()
print(a())
a = funX()
print(a())
'''
#例子2结果:
6
6
6
'''
参考:https://blog.csdn.net/beautiful77moon/article/details/87023824