闭包格式:
def 外函数():
def 内函数():
内函数操作外函数数据代码
return 内函数名
反面例子:
#定义工作函数
def work():
global money
money+=100
work() #工作一天
print(money)
work() #工作两天
print(money)
#天有不测风云钱被抢了
money = 0
print(money)#由于就近原则则money直接变为零了
正面例子:
def person():
money = 0
def work_1():
nonlocal money
money+=150
print(money)
return work_1 #闭包这里要返回内层函数
res = person() #根据等量代换 res等同于work_1
res()
res()
money=0
res() #没有修改,因为这里是封闭的,闭包保护私有数据不被改变