Closure (computer Science) - Example

Example

The following fragment of Python 3 code defines a function counter with a local variable x and a nested function increment. This nested function increment has access to x, which from its point of view is a non-local variable. The function counter returns a closure containing a reference to the function increment and increment's non-local variable x.

def counter: x = 0 def increment(y): nonlocal x x += y print(x) return increment

The closure returned by counter can be assigned to a variable:

counter1_increment = counter counter2_increment = counter

Invoking increment through the closures will give the following results:

counter1_increment(1) # prints 1 counter1_increment(7) # prints 8 counter2_increment(1) # prints 1 counter1_increment(1) # prints 9

Read more about this topic:  Closure (computer Science)

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)