Can you explain closures (as they relate to Python)?

I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.


Closure on closures

Objects are data with methods attached, closures are functions with data attached.

def make_counter():
    i = 0
    def counter(): # counter() is a closure
        nonlocal i
        i += 1
        return i
    return counter

c1 = make_counter()
c2 = make_counter()

print (c1(), c1(), c2(), c2())
# -> 1 2 1 2

It's simple: A function that references variables from a containing scope, potentially after flow-of-control has left that scope. That last bit is very useful:

>>> def makeConstantAdder(x):
...     constant = x
...     def adder(y):
...         return y + constant
...     return adder
... 
>>> f = makeConstantAdder(12)
>>> f(3)
15
>>> g = makeConstantAdder(4)
>>> g(3)
7

Note that 12 and 4 have "disappeared" inside f and g, respectively, this feature is what make f and g proper closures.


I like this rough, succinct definition:

A function that can refer to environments that are no longer active.

I'd add

A closure allows you to bind variables into a function without passing them as parameters.

Decorators which accept parameters are a common use for closures. Closures are a common implementation mechanism for that sort of "function factory". I frequently choose to use closures in the Strategy Pattern when the strategy is modified by data at run-time.

In a language that allows anonymous block definition -- eg, Ruby, C# -- closures can be used to implement (what amount to) novel new control structures. The lack of anonymous blocks is among the limitations of closures in Python.

链接地址: http://www.djcxy.com/p/1450.html

上一篇: 什么是创建单一的正确方法

下一篇: 你能解释关闭(因为它们与Python有关)吗?