装饰器:
装饰器本质上是一个 Python 函数或类,它可以让其他函数或类在不需要做任何代码修改的前提下增加额外功能,装饰器的返回值也是一个函数/类对象。
有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码到装饰器中并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。
Python的decorator可以用函数实现,也可以用类实现。
https://foofish.net/python-decorator.html
闭包:
闭包本质上是一个函数,它有两部分组成,printer
函数和变量 msg
。闭包使得这些变量的值始终保存在内存中。
def print_msg(): # print_msg 是外围函数 msg = "zen of python" def printer(): # printer 是嵌套函数 print(msg) return printeranother = print_msg()# 输出 zen of pythonanother()
一般情况下,函数中的局部变量仅在函数的执行期间可用,一旦 print_msg()
执行过后,我们会认为 msg
变量将不再可用。然而,在这里我们发现 print_msg 执行完之后,在调用 another 的时候 msg 变量的值正常输出了,这就是闭包的作用,闭包使得局部变量在函数外被访问成为可能。