闭包的概念:函数 + 特定环境中的变量
变量是一层一层往上级查找的,变量实在环境中存在的
一、第一步
# 第一步 def curve_pre(): # 变量作用域的实例 def cureve(): # 该函数的作用域是在函数curve_pre函数中 print('this is ok') return cureve # cureve()这个是不能直接被调用的,因为这里存在一个作用域的问题 f = curve_pre() f() # this is ok
二、第二步
# 第二步 def curve_pre(): a = 25 # a是在curve_pre函数中的变量,可以在cureve函数中被使用到 def cureve(x): return a * x * x return cureve f = curve_pre() res = f(2) print(res) # 100
三、第三步
# 第三步 def curve_pre(): a = 25 def cureve(x): return a * x * x return cureve a = 10 # 即使这里的a是全局的变量,但是在cureve()函数中会一步一步的往上级查找 # 会先在cueve_pre()函数中找到a变量,如果cueve_pre()如果还没有a变量的话,才会继续往上找全局变量a f = curve_pre() print(f.__closure__) # (<cell at 0x00000190B75176A8: int object at 0x000000005AEE6F10>,)是一个对象 print(f.__closure__[0].cell_contents) # 25 闭包的环境变量 res = f(2) print(res) # 100
四、第四步
# 第四步 def curve_pre(m): a = m def cureve(x): return a * x * x return cureve f = curve_pre(10) print(f.__closure__[0].cell_contents) # 10 闭包的环境变量 res = f(2) print(res) # 40
五、理解变量作用域
def f1(): a = 10 def f2(): a = 20 print(a) # 第二个打印 print(a) # 第一个打印 f2() print(a) # 第三个打印
f1() # 打印结果 # 10 # 20 # 10
六、python中global 和 nonlocal 的作用域
python引用变量的顺序: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量 。
global
1、 globalglobal关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字。
2、声明全局变量,如果在局部要对全局变量修改,需要在局部也要先声明该全局变量:
3、在局部如果不声明全局变量,并且不修改全局变量。则可以正常使用全局变量:
nonlocal
1、nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。
2、使用nonlocal关键字,也是需要提前声明的
浙公网安备 33010602011771号