闭包的更好插图? [英] Better illustration of Closures?
问题描述
我正在使用深入Python 3 书来学习Python。我喜欢它,但我不理解用于引入闭包的示例在6.5节中。
I am learning Python using Dive Into Python 3 book. I like it, but I don't understand the example used to introduce Closures in Section 6.5.
我的意思是,我知道它是如何工作的,而且我认为它真的很酷。但是我看不出任何真正的好处:在我看来,只需简单地逐行循环读取rules文件,并对每行读取进行搜索/替换,就可以实现相同的结果。
I mean, I see how it works, and I think it's really cool. But I don't see any real benefit: it seems to me the same result could be achieved by simply reading in the rules file line by line in a loop, and doing search / replace for each line read.
有人可以帮助我吗?
-
都可以理解为什么在本例中使用闭包可以改善代码(例如,是否更易于维护,扩展,重用或调试?)
either understand why using closures in this example improves the code (e.g., easier to maintain, extend, reuse, or debug?)
或建议其他一些真实的代码示例,其中闭包确实很出色?
or suggest a source of some other real-life code examples where closures really shine?
推荐答案
装饰器是闭包的示例。例如,
Decorators are an example of closures. For example,
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。闭包是允许您访问它的东西。
The function wrapped_function
is a closure, because it retains access to the variables in its scope--in particular, the parameter f, the original function. Closures are what allow you to access it.
闭包还允许您在函数调用之间保留状态,而不必诉诸类:
Closures also allow you to retain state across calls of a function, without having to resort to a class:
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())
此外,绑定方法在技术上是闭包(尽管实现方式可能不同) 。绑定方法是类成员函数,其类在以下类中烘焙:
Also, bound methods are technically closures (though they're probably implemented differently). Bound methods are class member functions with their class baked in:
import sys
w = sys.stdout.write
w("Hello\n")
w
本质上是对 sys.stdout
对象的引用。
w
is essentially a closure with a reference to the sys.stdout
object.
最后,我还没有没读过这本书,但快速阅读了您链接的章节,我对此并没有留下深刻的印象-它是如此的round回,以至于无法作为闭包的解释。
Finally, I haven't read that book, but a quick read of the chapter you linked and I'm very unimpressed--it's so horribly roundabout that it's useless as an explanation of closures.
这篇关于闭包的更好插图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!