Python full Stack---5.1---decorator

Source: Internet
Author: User

First, the decoration device

Adorners can perform other additional functions before and after a function is executed, a way to dynamically add functionality during code runs, called an "adorner" (Decorator), which is very powerful, but difficult to understand, so I try to explain this principle step-by-step with the simplest example.

Writing code to follow the development of the closure principle, although in this principle is used in object-oriented development, but also for functional programming, in short, it stipulates that the implemented function code is not allowed to be modified, but can be extended, namely:

    • Closed: Implemented function code block
    • Open: For extended development

1, without parameters of the adorner:

Suppose I define a function f, want to not change the original function definition of the case, before the function to print out the start, the function after the run to print the end, to implement such a function how to implement? See below how to use a simple adorner to achieve:

# using the @ syntax is equivalent to executing f=outer (f), at which point the F assignment becomes a new outer function, # at which point the F function points to the return value of the outer function Inner,inner is a function name, defined in the Oute function # The original F is the function name can be simply understood as a variable, as the parameters of the outer function passed in the argument Func equivalent to F def outer (func):                    # defines a outer function as the adorner     def inner (): # If The steps to execute the inner () function are as follows: Print         (' start ')              # 1, first printing the character ' start ',         R=func ()                    # 2, executing the Func function, the Func function equivalent to Def f (): Print (' Medium ')          print (' End ')                # 3, then the function prints ' end '         return r                    # 4, returning the result of the Func function to return     inner   @outerdef F ():              # F=outer (f) =innner     print (' Medium ')   f ()                   # f () is equivalent to inner (), the steps to perform the inner function look at the comment above the definition above <br># The order of printing results is   

2. adorners with arbitrary parameters:

In practice, our adorners may be applied to different functions, the parameters of these functions are not the same, then how do we implement a function for any parameter can implement the adorner? Remember when I wrote the function that blog, I wrote a function that can accept arbitrary parameters, and then see how to apply it to the adorner.

#其实只要将上面一种不带参数的装饰器修改一下就可以了 #修改也很简单, you can simply change the parameters of inner and Func to (*args,**kwargs) #其他实现的过程和上面一种一样 and no longer introduce the DEF outer (func):     def inner (*args,**kwargs):         print (' start ')         R=func (*args,**kwargs)    # here func (*args,**kwargs) equals F (A, B)         print (' End ')         return R     return inner   @outerdef F (A, B):     print (a+b) f (1,4)          

3. Use two adorners:

When a decorator is not enough, we can use two adorners, of course, it is more complicated to understand, when using two adorners, first the function with the inner decorator and then in conjunction with the outer adorner, to understand the use of the @ syntax when exactly what is done, is to understand the key to the adorner. Here is the simplest example to illustrate.

def outer2 (FUNC2): def inner2 (*args,**kwargs): Print (' Start ') r=func2 (*args,**kwargs) print (' End ') Return R return inner2 def outer1 (func1): def inner1 (*args,**kwargs): Print (' Start ') r= Func1 (*args,**kwargs) print (' End ') return R return inner1 @outer2 # this Equivalent to F=outer1 (f) F=outer2 (f), the steps are as follows @outer1 #1, F=outer1 (f) F is re-assigned the return value of Outer1 (1) inner1, DE F f (): # At this point the func1 is F ():p rint (' F function ') print (' F function ') #2, F=outer2 (f) Similar to F=outer2 (Inner1) f is re-assigned to the return value of Outer2 Inner2 # at this time Func2 for Inner1 function inner1 inside the FUNC1 function is the original                                    F ():p rint (' F function ') f ()                         # equivalent to execute Outer2 (inner1) () >> Start # in outer function, first print ' Start ' >>start        # Execute FUNC2 that executes Inner1 function print ' Start ' >>f function # inside the Inner1 function execute func1 i.e. f () function, print ' f function '                                 >>end # f function executes, then executes print (' End ') in Inner1 function >> end  # finally executes the print (' End ') inside the Inner2 function

4, with parameters of the adorner:

The front of the adorner itself without parameters, if you want to write a parameter of the adorner, then we need to write a three-layer adorner, and the front of the adorner is not too standard, the following to write a comparison specification with parameters of the adorner, the following to see the code, you can run the following code self-

Import Functools   def log (k= "):                                      #这里参数定义的是一个默认参数, if there are no parameters passed in, the default is null, can be replaced with other types of parameters     def decorator (func):         @ Functools.wraps (func)                      #这一句的功能是使被装饰器装饰的函数的函数名不被改变,         def wrapper (*args, **kwargs):             print (' Start ')             Print (' {}:{} '. Format (k, func.__name__))    #这里使用了装饰器的参数k             r = func (*args, **kwargs)             print (' End ')             Return r         return wrapper     return decorator   @log ()                        # Fun1=log () (FUN1) adorner does not use the parameter Def fun1 (a):     Print (A +) fun1 (+) # print   (fun1.__name__)        # Top Adorner if there is no @functools.wraps (func), the function printed here is called wrapper The   @log (' Excute ')                # fun2=log (' Excute ') (FUN2) adorner uses the given parameter Def fun2 (a):     
Double-decked adorner:

Can a function be decorated by multiple adorners? Like two decorators.

The function will be handed to the lowest-level @ adorner will process the results in the upper layer at the end of the adorner is given to W2 and then to W1

def W1 (func):    def Inner (*args,**kwargs):        # verify 1        # verify 2        # Verify 3        return func (*args,**kwargs)    return Inner def W2 (func):    def Inner (*args,**kwargs):        # verify 1        # verify 2        # Verify 3        return func (*args,** Kwargs)    return inner  @w1 @w2def F1 (ARG1,ARG2,ARG3):    print ' F1 '

Principle of double-decked decorator

Python full Stack---5.1---decorator

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.