"Python" Adorner

Source: Internet
Author: User

Source: Liu Xuefeng

Saw many times the decorator, found or Liao teacher speak well, can let me understand ...

Here is a piece of decorator code

@log def Now ():     Print " 20161107 "

Its meaning is equivalent to

def Now ():     Print " 20161107 "  = log (now)

That is, log is a function that takes a function to make a parameter, now becomes the return value of log

Below, add a simple log function, nested only one layer.

def log (func):     Print ' Call %s (): ' % func. __name__    return Func@log def Now ():     Print " 20161107 "
Print "-----"
Now ()

Results

Call Now ():-----20161107

The name of the called function is printed in the log function, but it will only run once, at the time of definition. Each time you run the now function, the result is the same as without the adorner.

Two-tiered nesting

def log (func):     def Wrapper (*args, * *kw)        :print'call%s ():' % func.  __name__        return func (*args, * *kw    )return  wrapper@log def Now ():     Print " 20161107 " print "-----"
Now ()
Now ()
Print now.__name__

Results

-----Call Now():20161107 Call Now():20161107
Wrapper

As you can see, in two tiers of nesting, you can implement a function name that is printed every time you run the now function.

After the use of log decoration, Now=log (now) is the wrapper function, the wrapper function is sealed in the original, and the use of variable parameters, to ensure that the wrapper can receive the now function of the variable. The function name is printed in wrapper and the result of the original now function is returned.

The problem is that when you print the name, now.__name__ has become wrapper. It is necessary to copy the properties of the original function __name__ into the wrapper() function, otherwise, some code that relies on the signature of the function will be executed in error.

There is no need to write wrapper.__name__ = func.__name__ such code, Python functools.wraps is built to do this, so a complete decorator is written as follows

Import Functools def log (func):    @functools. Wraps (func)    def Wrapper (*args, * *kw)        :Print  'call%s ():' % func. __name__        return func (*args, * *kw    )return Wrapper

Three-layer nesting for adorner parameters

Adorners can also have parameters, such as @log ("123")

Here is an example

defLog (*ARGS0, * *kw0):defDecorator (func):defWrapper (*ARGS1, * *kw1):ifLen (args0) = =0:Print "args0 = None"            Else:                PrintArgs0ifLen (kw0) = =0:Print "kw0 = None"            Else:                Printkw0returnFunc (*ARGS1, * *kw1)returnwrapperreturnDecorator@log ("Huhuhuhu")defA (x, y):Print "A"    returnX +Y@log ()defb ():Print "B"@log ("C", T=1, e=2, s=3)defC ():Print "C"A= A (3,2)PrintAPrint "------------"B ()Print "------------"C ()

Results

('huhuhuhu'= nonea5------------== noneb- -----------('C',) {'s'  'e't': 1}c

The meaning of the @log ("Huhuhuhu") is:

now = log ("Huhuhuhu") (now)

= Decorator (now)

= Wrapper

As you can see, the adorner parameters are implemented by adding a layer of nesting

"Python" Adorner

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.