Talk about closures in Python-Closure

Source: Internet
Author: User

Reprinted from 1190000007321972

A closure in Python is not a concept that can be understood, but as you go deeper into your study, you need to know something about it anyway.

The concept of closures

We try to understand the closure in terms of concept.

In some languages, when you can (nest) define another function in a function, a closure may be generated if the internal function refers to a variable of an external function. Closures can be used to create association relationships between a function and a set of "private" variables. These private variables maintain their persistence in the process of being called multiple times for a given function.
--Wikipedia)

It is easy to understand that when a function is returned as an object, an external variable is taken and a closure is formed. See example.

def Make_printer (msg):     def printer ():         Print msg  #  entrainment Sihuo (external variable)return     printer  #  returns the function , the function  with Sihuo = Make_printer ('foo! ' ) printer ()

A programming language that supports the use of functions as objects generally supports closures. Like Python, JavaScript.

How to understand closures

What is the meaning of closures? Why do I need closures?

I personally think that the meaning of a closure is that it carries an external variable (Sihuo), and if it does not carry Sihuo, it has no difference from the normal function. Different functions are implemented by the same function with different Sihuo . In fact, you can also understand that closures and interface-oriented programming are similar concepts that can be used to understand the closure of the package as a lightweight interface.

The interface defines a set of constraint rules for method signatures.

deftag (tag_name):defAdd_tag (content):return "<{0}>{1}</{0}>". Format (tag_name, content)returnadd_tagcontent='Hello'Add_tag= Tag ('a')PrintAdd_tag (content)#<a>Hello</a>Add_tag= Tag ('b')PrintAdd_tag (content)#<b>Hello</b>

In this example, we want an content add-on tag function, but the specifics of tag_name what it looks like to be based on the actual demand, the interface to the external call has been determined, that is add_tag(content) . If implemented by an interface-oriented approach, we will first add_tag write the interface, specify its parameters and return type, and then to implement A and B respectively add_tag .

But in the concept of closures, add_tag it is a function that requires tag_name and content two parameters, except that tag_name the parameter is packaged and taken away. So at first you can tell me how to pack and then take it.

The above example is not very vivid, in fact, in our lives and work, the concept of closures is also very common. For example, mobile phone dialing, you only care about the phone call to who, but not to struggle with each brand of mobile phone is how to achieve, the use of which modules. For example, to eat in a restaurant, you can pay to enjoy the service, you do not know that table food with how much gutter oil. These can be thought of as closures, returning to features or services (calling, dining), but these functions use external variables (antennas, gutter oil, etc.).

You can also think of a class instance as a closure, and when you construct the class, you use different parameters, which are the packets in the closure, and the method that this class provides is the function of the closure. But classes are much larger than closures, because closures are just a function that can be executed, but class instances can provide many methods.

When to use closures

In fact, closures are common in python, but you're not particularly aware that this is a closure. For example, in Python, the adorner decorator, if you need to write an adorner with parameters, then generally will generate closures.

Why? Because the python adorner is a fixed form of function interface. It requires that your adorner function (or adorner class) must accept a function and return a function:

#How to definedefWrapper (FUNC1):#accept a Callable object    returnFunc2#returns an object, typically a function    # How to usedefTarget_func (args):#objective Function    Pass#call way one, direct packageresult =Wrapper (Target_func) (args)#Call mode two, using the @ syntax, equivalent to the way one@wrapperdefTarget_func (args):Passresult= Target_func ()

So what if your decorator has parameters? Then you need to wrap a layer on the original adorner to receive these parameters. When these parameters (Sihuo) are passed into the inner adorner, the closure is formed. So when your decorator needs custom parameters, it usually forms a closure. (Class adorner exception)

defhtml_tags (tag_name):defWrapper_ (func):defWrapper (*args, * *Kwargs): Content= Func (*args, * *Kwargs)return "<{tag}>{content}</{tag}>". Format (Tag=tag_name, content=content)returnwrapperreturnWrapper_@html_tags ('b')defHello (name='Toby'):    return 'Hello {}!'. Format (name)#Do not use @ the following#Hello = Html_tag (' b ') (hello)#Html_tag (' B ') is a closure that takes a function and returns a functionPrintHello ()#<b>hello toby!</b>PrintHello' World')#<b>hello world!</b>
Go a little deeper.

In fact, it doesn't have to be too deep to understand the concept above, and many of the code that looks like a headache.

Let's take a look at what the closure package looks like. In fact, the closure function relative to the normal function will have a __closure__ property, which defines a tuple to hold all the cell objects, each cell object one by one holds the closure of all the external variables.

>>>defMake_printer (MSG1, MSG2):defprinter ():PrintMSG1, MSG2returnPrinter>>> printer = Make_printer ('Foo','Bar')#form Closures>>> printer.__closure__   #return cell tuple(<cell at 0x03a10930:str object at 0x039da218>, <cell at 0x03a10910:str object at 0x039da488>)>>> printer.__closure__[0].cell_contents#First external variable'Foo'>>> printer.__closure__[1].cell_contents#Second external variable'Bar'

The principle is so simple.

Reference links
    • Https://www.the5fire.com/clos ...

    • Http://stackoverflow.com/ques ...

Talk about closures in Python-Closure

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.