- 食用说明:本笔记适用于有一定编程基础的伙伴们。希望有助于各位!
闭包
在使用闭包之前,我们需要了解:

def mod2(salary):
def add(num):
nonlocal salary
salary += num
def minus(num):
nonlocal salary
salary -= num
def getSalary():
nonlocal salary
print(salary)
return add, minus, getSalary
def mod3():
salaryActions = mod2(0)
salaryActions[0](1000)
salaryActions[1](100)
salaryActions[2]()
if __name__ == '__main__':
mod3()
pass
- 上面的这个例子中,我们做了一个简单的工资存取的功能
- 其中nonlocal可以将一个局部变量,强制锁定为当前代码块的变量,而这也导致了内存空间无法被释放
装饰器
在闭包的基础上,我们可以将一些方法进行重构,比如下面的例子:
def myPrint(where: str):
def speak(what: str):
nonlocal where
print('[' + where + ']', end=':')
print(what)
return speak
wPrint = myPrint('Server')
wPrint('Hello')
- 此代码将传回一个新的方法,用于包装我们的新print方法


1079

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



