Definition of closures:
A closure is a function that remembers values in the enclosing scope, regardless of whether the enclosing scope is still in memory.
Here's an example:
Def Happy_add (a): print ' ID (a):%x '% ID (a) def do_add (b): return a + B print ' ID (do_add):%x '% ID (do_add ) Return do_addtest_one = Happy_add (1) test_one (9) Print repr (test_one) print ' \ n------------------\ n ' test_other = Happy_add (3) del happy_addtest_other (+) print repr (test_other)
The execution results are:
ID (a): 7fae91d05788id (do_add): 10a94a0c8<function do_add at 0x10a94a0c8>------------------ID (a): 7fae91d05758id (do_add): 10a94a6e0<function Do_add at 0x10a94a6e0>
Analysis:
The first ID (x) is to find the address in memory of X.
Two times ID (a) differs, stating that the variable is bound to its own nested function object.
Each call to Happy_add () produces different objects, which are stored in different places.
Enclosing namespace deletion (Del Happy_add) also does not affect the execution of the closure function.
In this way a function is written as class:
Class Happy_add: def __init__ (self, x, y): self.x = x self.y = y def add (self): return self.x + self.y Test_one = Happy_add (1, 9) print Test_one.add ()
is not very beautiful, kind of a fuss feeling.
Closure of the judgment:
(1) A nested function (function inside the function)
(2) The nested function uses one or more values defined in the enclosing function
(3) The return value of the enclosing function is a nested function
When to use closures:
The benefit of closures is to avoid using global variables and provide an optional form of data hiding. The problem is that these can all be achieved through class, why should there be closure? Typically, classes are used when there are many properties and methods. Conversely (in most cases a method), choosing Closure,closure will be a more elegant and concise solution.
Python Closure (closure)