免费的app软件下载网站,自己如何制作一个微信小程序,诗歌网站开发意义,阿里巴巴网站分类导航做全屏闭包
在函数嵌套的前提下#xff0c;内部函数使用了外部函数的变量#xff0c;并且外部函数返回了内部函数#xff0c;我们把这个使用外部函数变量的内部函数称为闭包。
简单闭包
内部函数使用外部变量
def outer(name):def inner(name1):print(f{name}内部函数使用了外部函数的变量并且外部函数返回了内部函数我们把这个使用外部函数变量的内部函数称为闭包。
简单闭包
内部函数使用外部变量
def outer(name):def inner(name1):print(f{name}{name1}{name})return innerf1 outer(wyx)
f1(sxx)f2 outer(sx)
f2(wyx)
wyxsxxwyx
sxwyxsx
nonlocal关键字
如果需要修改外部函数变量的值需要使用nonlocal关键字修饰外部函数的变量才可以在内部函数中修改它。
def outer(num1):def inner(num2):nonlocal num1num1 num2print(num1)return innerfn outer(10)
fn(10) #20
fn(10) #30
account 0
def atm(num, depositTrue):global accountif deposit:account numprint(f存款{num},余额{account})else:account - numprint(f取款-{num},余额{account})atm(300)
atm(100, False)
存款300,余额300
取款-100,余额200#使用闭包实现
def account(amount0):def atm(num, depositTrue):nonlocal amountif deposit:amount numprint(f存款{num},余额{amount})else:amount - numprint(f取款-{num},余额{amount})return atmatm account()
atm(100)
atm(200)
存款100,余额100
存款200,余额300
注意事项
优点使用闭包可以让我们得到 无需定义全局变量即可实现通过函数持续的访问修改某个值 闭包使用的变量的所用于在函数内难以被错误的调用修改
缺点 由于内部函数持续引用外部函数的值所以会导致这一部分内存空间不被释放一直占用内存
装饰器
装饰器其实也是一种闭包其功能就是在不破坏目标函数原有的代码和功能的前提下为目标函数增加新功能。
def outer(func):def inner():print(我要睡觉了)func()print(我要起床了)return innerdef sleep():import randomimport timeprint(睡眠中。。)time.sleep(random.randint(1,4))fn outer(sleep)
fn()
我要睡觉了
睡眠中。。
我要起床了装饰器的语法糖写法
使用outer定义在目标函数sleep之上
def outer(func):def inner():print(我要睡觉了)func()print(我要起床了)return innerouterdef sleep():import randomimport timeprint(睡眠中。。)time.sleep(random.randint(1,4))sleep()