视频21
1.内部函数作用域 都在外部函数之内
例一
>>> def fun1():
print('fun1正在被调用···')
def fun2():
print('fun2正在被调用···')
fun2()
>>> fun1()
fun1正在被调用···
fun2正在被调用···
>>> fun2()
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
fun2()
NameError: name 'fun2' is not defined2.闭包closure(定义:如果在一个内部函数里,对外部作用域(非全局作用域)的变量进行引用,那么内部函数被称为闭包)
闭包需要满足以下三个条件:
①存在于嵌套关系的函数中
②嵌套的内部函数引用了外部函数的变量
③嵌套的外部函数会将内部函数名作为返回值返回
闭包需要满足以下三个条件:
①存在于嵌套关系的函数中
②嵌套的内部函数引用了外部函数的变量
③嵌套的外部函数会将内部函数名作为返回值返回
例
>>> def outer(start=0):
count = [start]
def inner():
count[0] += 1
return count[0]
return inner
>>> out = outer(5)
>>> print(out())
6例二
>>> def funx(x):
def funy(y):
return x*y
return funy
>>> i = funx(8)
>>> i
<function funx.<locals>.funy at 0x00000232BDFFC840>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> funx(8)(5)
40
例三
>>> def fun1():
x = 5
def fun2():
x *=x
return x
return fun2()
>>> fun1()
Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
fun1()
File "<pyshell#59>", line 6, in fun1
return fun2()
File "<pyshell#59>", line 4, in fun2
x *=x
UnboundLocalError: local variable 'x' referenced before assignment在赋值前引用的局部变量x
#运行至return fun2(),内部函数试图修改全局变量(相对而言),Python用shadowing隐藏全局变量(相对而言),即在内部函数fun2()的外部空间中的x = 5被屏蔽,故x未被赋值
#运行至return fun2(),内部函数试图修改全局变量(相对而言),Python用shadowing隐藏全局变量(相对而言),即在内部函数fun2()的外部空间中的x = 5被屏蔽,故x未被赋值
容器类型对代码改造(1.列表不是存放在栈里面,是一个单独的容器,所以在内部函数里可以进行修改2.列表储存在堆内存中,相当于都是全局变量)
例三
>>> def fun1():
x = [5]
def fun2():
x[0] *=x[0]
return x[0]
return fun2()
>>> fun1()
25
#关键字nonlocal改造
>>> def fun1():
x = 5
def fun2():
nonlocal x
x *=x
return x
return fun2()
>>> fun1()
25
>>>
3682

被折叠的 条评论
为什么被折叠?



