Python's Path to self-study--The Secret of decorators

Source: Internet
Author: User

No matter what the adorner is, let's talk about some of the functions. We know that in Python, everything is the object, then the function, of course, is also the object, and people are a first-class object. Since it is an object, it can be assigned to a variable, whereas a function can be called by a variable. OK, to pay special attention to the point, the function call must be the function name + (), if there is no this parenthesis, the function is not called, it can only represent an address in memory, see below

1 def Happy (): 2     Print ('behappy') 3 Print # does not call the happy function, just prints the address of happy 4 # Call the Happy function
<function Happy at 0x0000014b53c1f048> ishappy

Let's take a look at the example of the function being assigned as a variable.

For the happy function, what if I want to add a name before be happy? We will, of course, add

1 def Happy (): 2     Print ('mumu') 3     Print ('behappy')

However, we have not thought, so we will break the original happy this function, and, if you need to modify the function of a bit larger, difficult we still have to go inside to change it? This scene is certainly not allowed, so we have figured out a way ...

1 defHappy ():2     Print('Be Happy')3 defName (func):4     Print('Mumu')5     returnfunc6Happy =name (happy)7 Happy ()8 Print(Happy.__name__, name.__name__,)
Mumube happyhappy Name

Have you found that the most magical sentence in the above code is happy = name (happy), through which Python passes the address of happy to the name function, let the name function execute its code (that is, add a name) and return the happy address, Finally call happy. In this way, we have not changed the happy function under the premise of the implementation of the demand, is not very bad? In fact, this is the secret of the decorator!

However, since the person is a decorator, it certainly will not be the same as other code like Ah, watch, people's form but this kind of @+ function name Let's see what the code looks like with a real decorator.

1 defName (func):2     Print('Mumu')3     returnfunc4 @name5 defHappy ():6     Print('Be Happy')7 Happy ()8 Print(Happy.__name__, name.__name__,)

Do not assume that the adorner is so simple oh, a slightly more difficult example, let's take this example to take a good look at the decorator in the Python interpreter principle

Let's take a look at the difference between the following two programs

Written here, is it not found that we have no parameters of the adorner, add a parameter to the function let's see

defName (func):defInner (ARG):Print('Mumu')        returnfunc (ARG)returnInner@namedefHappy (user):Print('%s Be Happy'%user)return "ye!"ret= Happy ('must')Print('return Value:', ret)
Mumumust Be happy return value: ye!

The example simply gives a parameter, if you want multiple parameters, even many different classes of parameters, with the universal parameters *args,**kwargs Bai

Now we should understand that the decorator is actually a layer of function outside the original function, so that when we call the original function is called the adorner returned to you the function, then, we think, the adorner can be multiple, one by one to the function of the set? The answer is yes, just look at the example of two adorners, in fact, I think, a number of adorners are not necessary, so complicated ...

1 defOuter1 (func):2     definner ():3         Print('O1,before')4 func ()5         Print('O1,after')6     returnInner7 8 defOuter2 (func):9     definner ():Ten         Print('O2,before') One func () A         Print('O2,after') -     returnInner -  the @outer2 - @outer1 - defHappy (): -     Print('Happy Everyday') +  -Happy ()

O2,beforeo1,beforehappy Everydayo1,aftero2,after

For such a plurality of adorners we can understand that it is like a Russian set of baby, the innermost primitive function is the outside of the adorner function layer by nest, the function name of the original function is passed to the adorner closest to it, the inner decorator return value will be passed to the outer adorner parameters.

Python's Path to self-study--The Secret of decorators

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.