Python Closure (closure)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.