max*_*max 13 python closures python-3.x
我正在使用Dive Into Python 3学习Python .我喜欢它,但我不理解6.5节中用于介绍Closures的示例.
我的意思是,我知道它是如何工作的,我觉得这很酷.但我没有看到任何真正的好处:在我看来,通过简单地在循环中逐行读取规则文件,并对每行读取进行搜索/替换,可以实现相同的结果.
有人可以帮助我:
或者理解为什么在这个例子中使用闭包改进了代码(例如,更容易维护,扩展,重用或调试?)
或建议一些其他真实代码示例的来源,其中闭包真正发光?
谢谢!
Gle*_*ard 25
装饰器是闭包的一个例子.例如,
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()
Run Code Online (Sandbox Code Playgroud)
该函数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())
Run Code Online (Sandbox Code Playgroud)
此外,绑定方法在技术上是闭包(尽管它们可能以不同方式实现).绑定方法是类成员函数,其类烘焙在:
import sys
w = sys.stdout.write
w("Hello\n")
Run Code Online (Sandbox Code Playgroud)
w本质上是一个带有sys.stdout对象引用的闭包.
最后,我还没有看过那本书,但是你快速阅读了你所关联的章节,我对此非常不满意 - 它是如此可怕的迂回曲折,以至于它对闭包的解释毫无用处.
| 归档时间: |
|
| 查看次数: |
12999 次 |
| 最近记录: |