Road Python learning - function closure and decorator

Many initial contact to the python's junior partner may not understand what closures are, why closures, closures what use, then today from bloggers on the three points we explain python closure

First, what is closure

  • The official definition:
    In computer science, closures (English: Closure), also known as lexical closures (Lexical Closure) or a function closure (function closures), is a reference to the function of free variables. This free variables referenced and this function will exist together, even if it has left the creation of an environment is no exception. Therefore, there is another way of saying that the closure is a combination of entities and functions associated therewith environment references made. Closures can have multiple runtime instances, different reference environment and can generate the same function of a combination of different instances.

  • I understand
    within a nested function of a function, the function reference and an external local variables in the function, then this function is called internal closures

  • Closures Python

    Python implementation of closures due to Python is an object-oriented programming language, the function is no exception in Python, in Python function also as an object (function object) there is way
    below us look at an example you clear:
    Here Insert Picture Description
    here we first define a function, then we use internal methods in Python (type), the role of type (args) is to look at the incoming args parameter type, we can see the type of func is a function object
    we all know that the function can return values, so in Python function object or as a return value, thus providing the basis for the implementation of closures.

    : Here we look at Python closure realization
    Here Insert Picture Description
    inside where we first define a function called outer, and then inside of this function we define a variable called "out_value", and then again in the function It defines an internal function called inner and within the inner function we quoted an external variable function (outer), so we call for the inner closure

    We look at the closure of some of the properties
    Here Insert Picture Description
    we called and executed outer function and returned value to the variable f, we can see through print, the type variable f as a function of the type, because it is a function object f necessarily have ' _ Call _ '(that is, () is a function executed after the function) attributes and then we will look at the name of the variable f, you can see that f is a function object called inner, why this is so is because the implementation of the outer function after the completion, at the time of their return we will return in the inner function object defined inside the outer function, so the name of the variable to inner f

Now that we understand the basic implementation in python closures, then let us look at a few examples:
Here Insert Picture Description
The above example we see in the absence of answers, we guess what will happen, we might have some small partners have seen through this transmission of the disease, the result of a small partner did not see that part of the mind is not
0
1
2
? it so that I do not guessing here, in fact, above this result is wrong, the correct result is:
2
2
2
Why is this so?
that is because in the outer function, inner relative to the outer is just a function of its internal definition of the scope of the variable i in the outer or middle, so
now is not the inner to the outer closure, Therefore, change can change the value of i is the inside inner variable i when the last cycle is finished, the value of the variable i is i 2 will not change the time, and then returns a list of the closure, the printed should all 2

Then we can look at an example, if now I have a demand, the content is I need to have a function, I printed out the current many times to call, if you understand the iterator junior partner should be very easy to implement when this function is called, but there need to implement this function by way of closure, how to achieve it.
there may be a small partner will have the following ideas:
Here Insert Picture Description
but I regret to tell you that this approach is wrong, we may wish to look at the results:
Here Insert Picture Description
analysis cause of the error, probably mean that the local variable "cnt" in reference to the assignment before, it tells us can not be assigned after reference because the scope of this variable is in the external function, then how to solve this problem then, Python will provides a good a reserved word used to declare local variables (nonlocal keyword)
we look at the implementation of revised results:

Here Insert Picture Description
After nonlocal statement can be seen through the variable cnt get the results we want

Here is some explanation official closure process variable scope:
"" the Cell "Objects are referenced by Variables Used to Implement the For each SUCH variable Multiple Scopes, Created IS A to Cell Object Store The value; each of Variables The local. stack frame that references the value contains a reference to the cells from outer scopes which also use that variable. When the value is accessed, the value contained in the cell is used instead of the cell object itself. This de-referencing of the cell object the byte Generated from Support the requires-code; THESE are de-referenced When Not Automatically accessed to the Cell BE LIKELY objects are Not Useful Elsewhere. ".
" the Cell "objects referenced by the variables used to implement more than one scope. For each such variable, a cell object to create a stored value; reference a local variable stack frame for each value comprises a reference to the cell from the outside of the scope, also outside the scope of the variables used. When the value is accessed, the value contained in the cell, the cell rather than the object itself. Cancel reference cell object bytecode support needs to be generated; these references are not automatically canceled at the time of access. Cell object unlikely to be useful elsewhere.
So everyone should understand.

Second, why have closure

Closure avoids the use of global variables, in addition, closure and allows some of the data it operates on function (environment) connected together. This object-oriented programming is very similar, the surface of the object programming, objects allow us to some data (properties of the object) with one or more associated methods.

In general, when the object is only one way, then the use of closures is the better choice.
Here we use two different methods to achieve the same kind of demand, in that way you can know relatively more advantages:

Demand: We have a digital object named Number, we want to achieve their addition operation of law

  1. To achieve by category:
    Here Insert Picture Description
  2. Be achieved with closures

Here Insert Picture Description
We can see that can make the code when closures manner to achieve a more simple, which is why you want to use closures reasons.

Closure usefulness - decorator

Since speaking in front of so many closures of knowledge, and applications, then here is a look at the closure of the largest utility in Python, that is, "decorator."
Hearing the name, you know the role of decorator, decorator Well it is certainly used to decorate Well, that's what it is used to decorate it, in fact, used to decorate some of the objects in the Python.
may be small partners before understanding decorator, when exposed to the class to see there there are class methods above some special symbols.
like Here Insert Picture Description
keywords such as modified by the @ symbol is actually a decorator.
so let's define a simple decorator look:
Here Insert Picture Description
the above is our custom decorator a decorator, in the following we define the function f we use them to decorate decorator,
we found only within the original function f ">>>> being executed" line print information, but after a decorator decoration, it print information into a two-line,
is not it amazing, all for a reason, Secret now to look inside this mystery.
in fact, the role of the @ symbol here is to let the program automatically performs a Kind of statement "f = decorator (f)" We wish to see to know: Here Insert Picture Description
Hey, we found that we define the function f its name was changed to the wrapper, is not that what we decorator function returns closures Well, so combined with previous closures knowledge, we found that the decorator is actually not so difficult thing.

Well, let's look at some of the more sophisticated decorator deepen understanding:

  1. With reference decorator:
    Here Insert Picture Description
    when we achieve the above arguments passed to the decorator in practice, we took a name for the current function, and then in the implementation of print it out, we found that to be mass participation, our entire the nested function becomes three, and of course, the front working mechanism decorator with no parameters are similar, a new name. decorator with parameters were nothing more than f = set_name following operations during use of ( "Nick") (f) so that it should understand.
  2. Decorator function with parameters to be decorated questions:
    (1) The first approach: Here Insert Picture Description
    Obviously this approach is made out of decorative versatility is not strong, if we need to decorate a function parameter changes that occur on our decorator can not be used, and this is certainly unacceptable to us.
    (1) the second approach:
    Here Insert Picture Description
    and the same effect as the previous method, but using parcel and parcels keyword parameters parameters of mass participation, strong versatility on the lot, it is recommended write.

We are talking about the first decorator's time we found a problem, and that is a function decorator modified after the original function name change took place, have a unified name became the name of the function defined by our internal decorator, If I still want the original function name how to do it, do not worry there first approach the following:
Here Insert Picture Description
to do so is actually forced to change the name of its subject, such an approach it is certainly not so elegant, and also in Python not respected
us a more elegant look at the following wording:
Here Insert Picture Description
this time on the right, just like dad said we have to use magic against magic, here decorators decorators to solve the problem, it is more elegant many, and
if interested small partners may wish to think about their own thinking functools.wraps achieve this decorator, and then implement yourself once, I believe you learn decorators have some help here between space reasons do not explain the realization the idea.

  1. Use the execution sequence of multi-decorator
    times when we need more of a function decorators extended, how can we write, when a decorative function call hierarchy with multiple decorators order between the decorator and how , read the following example you will know:
    Here Insert Picture Description
    we can see when we needed more than decorate decorator, decorator only need to turn to overlap, the order of execution decorator it is performed sequentially down from above, that is why, we might combine stated before the @ symbol actually doing things in terms of (f = decorator (f))
    , this is nested between multiple decorators of the relationship between the nested chart from bottom to top the relationship is:
 f = decorator3(decorator2(decorator1(f)))
  1. Let's last example, we use the class way to achieve a decorator look:
    Here Insert Picture Description
    for class _ Call _ methods have already mentioned here is not talked about, calling the process here in front of the first and decorators embellishment is calling procedure is the same as f = MyDecorator (f) corresponding to an object f is a class instantiated by the MyDecorator out, when the object in the execution f f () is triggered in a __call__ method MyDecorator .

Well closures and decorators explanation came to an end, the junior partner in doubt welcome to ask questions, discuss aspects of Python knowledge together.

Published 27 original articles · won praise 62 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42359956/article/details/104729796