Deep understanding of closures and decorators in python

Source: Internet
Author: User
The following small series will bring you an in-depth understanding of the closures and decorations in python. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the closure in python. The definition (interpretation) in the form of representation is: if a variable in the external scope (but not in the global scope) is referenced in an internal function, the internal function is regarded as a closure ).

The following describes python2.7, which may vary with other versions.

You may not be able to understand the definition directly. Next let's look at what is called an internal function:

Def wai_hanshu (canshu_1): def nei_hanshu (canshu_2 ): # I have defined a function return canshu_1 * canshu_2 return nei_hanshu inside the function # I return the internal function a = wai_hanshu (123) # canshu_1 = 123 print aprint a (321) # canshu_2 = 321

I have nested a function in the function. when I pass a variable to the outer function and assign it to a, we find that a is a function object, when I pass parameters for this function object again, I obtain the internal function return value. We know that according to the scope principle, we cannot access the local scope in the global scope. However, the internal function is accessed through a clever method ..

Next we will continue to look at an example:

def wai_hanshu():  a = []  def nei_hanshu(canshu):    a.append(canshu)    return a  return nei_hanshua = wai_hanshu()print a(123)print a(321)

It can be seen that list a in the external function has changed. To know why, we need to first know what the python namespace is, and the namespace is the reason for the scope performance. here I will briefly describe it.

The main reason for the introduction of namespaces is to avoid variable conflicts, because there are many modules in python, functions and classes in the modules, and they all need to use variables. However, if you do not conflict with other variable names every time, it is too troublesome. developers should focus on their own problems, rather than considering what variables are used in programs written by others, therefore, python introduces namespaces. The namespace is divided into the module layer, and the module is divided into global scope and local scope, which are represented by a figure:

The namespaces are different between modules, and there are global scopes and local scopes in them. The local scopes can be nested before, so that the variable names do not conflict with each other. By the way, you can use the _ name _ attribute to obtain the namespace name:

The namespace of the main file is '_ main _', and the module namespace is the module name.

The emergence of the scope is because when python is looking for a variable, it will first look for it in the current namespace. if it does not exist in the current namespace, it will be found in the namespace at the upper level, similarly, if no exception is found at the end, an exception is triggered.

We have always said that the global scope cannot access the local scope, and the local scope can access the global scope. When I create a variable with the same name as an external variable in a local scope, python first finds the variable in the current scope, I will not continue to search for the above level.

In earlier versions of python, partial scopes cannot access other partial scopes, but can only access the global ones. The current versions are listed at the previous level.

Because of this feature, we can access variables in external functions in internal functions, which is also called closures.

Note: We need to differentiate objects here, for example:

Def wai_hanshu (): a = [] def nei_hanshu (canshu):. append (canshu) return a return nei_hanshua = wai_hanshu () # I created an object B = wai_hanshu () # I created another object print aprint bprint a (123) print B (321)

Although we operate all the variables in wai_hanshu, a and B are completely two objects, and their memory space is different, so the data in them is also independent. Be sure not to confuse.

Decorator

In fact, the decorator takes several more steps on the basis of the closure. check the code:

Def zsq (func): # decorate function def nei (): print 'perform some operations before the input function is executed. 'func () # execute the function print 'I will do something after the target function is executed.' return neidef login (): # Deprecated function print 'I have logged on to the function 'login = zsq (login) # I pass the decorated function into the decoration function and overwrite the original function entry login () # at this time, the decorated function is executed.

When reading this code, you need to know a few things:

1. the parameter of a function is actually a reference, not a value.

2. the function name is also a variable, so you can assign a value again.

3. when assigning values, perform the equal sign on the right.

After understanding the above things, you can combine the code to understand what a decorator is. The so-called decorator transmits a function based on the closure, and then overwrites the execution entry of the original function. when you call this function later, you can implement some additional functions. The decorator is mainly used to expand functions without modifying the code of the original function or modifying other code that calls this function.

Python thinks it is too inconvenient for you to perform the rename operation every time, so it provides a convenient method:

Def zsq (func): def nei (): print 'I do some operations before the passed-in function execution 'func () # execute the function print 'I will do something after the target function is executed' return nei @ zsq # automatically upload the following function as a parameter to the decoration function to def login (): print 'I have logged on to the function' login ()

These small conveniences are also called python syntax sugar, which you may have seen in many places.

Decorator with parameters:

Def zsq (a): print 'I am the decorator parameter', a def nei (func): print 'I do some operations before the passed-in function execution 'func () # execute the function print 'I will do something after the target function is executed.' return nei @ zsq ('000000') def login (): print 'I have logged on to the function'

Equivalent to: login = zsq (123) (login), so it is executed without calling it here.

Nest of the decorator:

An example is not complete here:

@deco1(deco_arg) @deco2 def func():   pass

Equivalent to: func = deco1 (deco_arg) (deco2 (func ))

That is, nesting from top to bottom.

We will talk about the closure and decorator first, and we will need to add it later.

The above in-depth understanding of the closure and decorator in python is all the content that I have shared with you. I hope to give you a reference and support for my own home.

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.