参考:

 ​​Python 函数装饰器 | 菜鸟教程​

一、什么是闭包

python中的闭包从表现形式上定义(解释)为:

如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure).

python中函数名是一个特殊的变量,它可以作为另一个函数的返回值,而闭包就是一个函数返回另一个函数后,其内部的局部变量还被另一个函数引用。

闭包的作用就是让一个变量能够常驻内存。

def func(name): # 定义外层函数
def inner_func(age): # 内层函数
print('name: ', name, ', age: ', age)

return inner_func # 注意此处要返回,才能体现闭包

if __name__ == '__main__':
bb = func('jayson') # 将字符串传给func函数,返回inner_func并赋值给变量
bb(28) # 通过变量调用func函数,传入参数,从而完成闭包

打印结果:

name:  jayson , age:  28

闭包的用途

两个用处:① 可以读取函数内部的变量,②让这些变量的值始终保持在内存中。

②让函数内部的局部变量始终保持在内存中:

怎么来理解这句话呢?一般来说,函数内部的局部变量在这个函数运行完以后,就会被Python的垃圾回收机制从内存中清除掉。如果我们希望这个局部变量能够长久的保存在内存中,那么就可以用闭包来实现这个功能。

这里借用
@千山飞雪
的例子(来自于:千山飞雪:深入浅出python闭包)。请看下面的代码。

以一个类似棋盘游戏的例子来说明。假设棋盘大小为50*50,左上角为坐标系原点(0,0),我需要一个函数,接收2个参数,分别为方向(direction),步长(step),该函数控制棋子的运动。 这里需要说明的是,每次运动的起点都是上次运动结束的终点。

def create(pos=[0,0]):

def go(direction, step):
new_x = pos[0]+direction[0]*step
new_y = pos[1]+direction[1]*step

pos[0] = new_x
pos[1] = new_y

return pos


return go

player = create()
print(player([1,0],10))
print(player([0,1],20))
print(player([-1,0],10))

在这段代码中,player实际上就是闭包go函数的一个实例对象。

它一共运行了三次,第一次是沿X轴前进了10来到[10,0],第二次是沿Y轴前进了20来到 [10, 20],,第三次是反方向沿X轴退了10来到[0, 20]。

这证明了,函数create中的局部变量pos一直保存在内存中,并没有在create调用后被自动清除。

为什么会这样呢?原因就在于create是go的父函数,而go被赋给了一个全局变量,这导致go始终在内存中,而go的存在依赖于create,因此create也始终在内存中,不会在调用结束后,被垃圾回收机制(garbage collection)回收。

这个时候,闭包使得函数的实例对象的内部变量,变得很像一个类的实例对象的属性,可以一直保存在内存中,并不断的对其进行运算。

二、装饰器(decorator)

装饰器就是为了不修改原函数的定义,并使原函数在运行时动态增加功能的方式,一般来说装饰器是一个返回函数的高阶函数。

简单地说:他们是修改其他函数的功能的函数。

装饰器让你在一个函数的前后去执行代码。

def hi(name="yasoob"):
def greet():
return "now you are in the greet() function"

def welcome():
return "now you are in the welcome() function"

if name == "yasoob":
return greet
else:
return welcome

a = hi()
print(a)
#outputs: <function greet at 0x7f2143c01500>

#上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
#现在试试这个

print(a())
#outputs: now you are in the greet() function

在 if/else 语句中我们返回 greet 和 welcome,而不是 greet() 和 welcome()。

当你把一对小括号放在函数后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。

蓝本规范:

from functools import wraps
def decorator_name(f):
@wraps(f)
def decorated(*args, **kwargs):
if not can_run:
return "Function will not run"
return f(*args, **kwargs)
return decorated

@decorator_name
def func():
return("Function is running")

can_run = True
print(func())
# Output: Function is running

can_run = False
print(func())
# Output: Function will not run

1、将被装饰的函数,作为一个变量,传入了装饰函数里

2、装饰函数,只有一个传参,那就是被装饰的函数

3、开始执行最外层return的这个函数,里面的变量就是被装饰的函数(传进来的函数)

其实有用的代码就这一块,其他乱七八糟的都要忽略掉,里面的那个变量,就是被传入的函数

python 闭包与装饰器_python

使用场景

授权(Authorization)

装饰器能有助于检查某个人是否被授权去使用一个web应用的端点(endpoint)。它们被大量使用于Flask和Django web框架中。这里是一个例子来使用基于装饰器的授权:

from functools import wraps

def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
authenticate()
return f(*args, **kwargs)
return decorated

有用的就这一小块

python 闭包与装饰器_git_02

日志(Logging)

日志是装饰器运用的另一个亮点。这是个例子:

from functools import wraps

def logit(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging

@logit
def addition_func(x):
"""Do some math."""
return x + x


result = addition_func(4)
# Output: addition_func was called

有用的就这一小块

python 闭包与装饰器_python_03

带参数的装饰器

在函数中嵌入装饰器

我们回到日志的例子,并创建一个包裹函数,能让我们指定一个用于输出的日志文件。

from functools import wraps

def logit(logfile='out.log'):
def logging_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
# 打开logfile,并写入内容
with open(logfile, 'a') as opened_file:
# 现在将日志打到指定的logfile
opened_file.write(log_string + '\n')
return func(*args, **kwargs)
return wrapped_function
return logging_decorator

@logit()
def myfunc1():
pass

myfunc1()
# Output: myfunc1 was called
# 现在一个叫做 out.log 的文件出现了,里面的内容就是上面的字符串

@logit(logfile='func2.log')
def myfunc2():
pass

myfunc2()
# Output: myfunc2 was called
# 现在一个叫做 func2.log 的文件出现了,里面的内容就是上面的字符串

1、有用的只有这一块

python 闭包与装饰器_局部变量_04

2、多包裹一层就是为了多传递一个参数