1. 闭包
a. 闭包的条件
在Python中创建闭包必须满足的条件:
- 我们必须有一个嵌套函数(函数在函数内部)。
- 嵌套函数必须引用在封闭函数中定义的值。
- 封闭函数必须返回嵌套函数。
b. 何时使用闭包?
闭包可以避免使用全局值,并提供某种形式的数据隐藏。它还可以为该问题提供面向对象的解决方案。
当在一个类中实现的方法很少(大多数情况下是一个方法)时,闭包可以提供另一种更优雅的解决方案。但是,当属性和方法的数量变大时,最好实现一个类。
def f(x):
def g(y):
return x + y
return g # Return a closure.
def h(x):
return lambda y: x + y # Return a closure.
# Assigning specific closures to variables.
a = f(1)
b = h(1)
# Using the closures stored in variables.
assert a(5) == 6
assert b(5) == 6
# Using closures without binding them to variables first.
assert f(1)(5) == 6 # f(1) is the closure.
assert h(1)(5) == 6 # h(1) is the closure.
2. 装饰器
from time import time, sleep
def runtime(f):
def inner(*args, **kwargs):
print(f'-- Function {f.__name__} start ...')
t = time()
result = f(*args, **kwargs)
print(f'-- Function {f.__name__} end. (Runtime: {time() - t:.3f} seconds)\n')
return result
return inner
@runtime
def func():
sleep(2)
if __name__ == '__main__':
func()
Output
-- Function func start ...
-- Function func end. (Runtime: 2.000 seconds)
参考资料:
[1] https://www.cainiaojc.com/python/python-closure.html
[2] https://en.wikipedia.org/wiki/Closure_(computer_programming)