我正在使用 Dive Into Python 3 学习 Python书。我喜欢它,但我不明白example used to introduce Closures在第 6.5 节中。
我的意思是,我看到它是如何工作的,我认为它真的很酷。但我没有看到任何真正的好处:在我看来,只需循环逐行读取规则文件,并对读取的每一行进行搜索/替换,就可以获得相同的结果。
谁能帮我:
理解为什么在此示例中使用闭包可以改进代码(例如,更易于维护、扩展、重用或调试?)
或者建议闭包真正发挥作用的其他一些真实代码示例的来源?
最佳答案
装饰器是闭包的一个例子。例如,
def decorate(f):
def wrapped_function():
print("Function is being called")
f()
print("Function call is finished")
return wrapped_function
@decorate
def my_function():
print("Hello world")
my_function()
函数 wrapped_function
是一个闭包,因为它保留了对其范围内变量的访问权——特别是原始函数的参数 f。闭包允许您访问它。
闭包还允许您在调用函数时保留状态,而不必求助于类:
def make_counter():
next_value = 0
def return_next_value():
nonlocal next_value
val = next_value
next_value += 1
return val
return return_next_value
my_first_counter = make_counter()
my_second_counter = make_counter()
print(my_first_counter())
print(my_second_counter())
print(my_first_counter())
print(my_second_counter())
print(my_first_counter())
print(my_second_counter())
此外,绑定(bind)方法在技术上是闭包(尽管它们的实现方式可能不同)。绑定(bind)方法是类成员函数,它们的类内置于:
import sys
w = sys.stdout.write
w("Hello\n")
w
本质上是一个引用了 sys.stdout
对象的闭包。
最后,我还没有读过那本书,但是快速阅读了您链接的那一章,我很不以为然——它太迂回了,作为闭包的解释毫无用处。
关于python - 更好地说明闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2796855/