Python full stack Development 8, decorator detailed

Source: Internet
Author: User
Tags function definition python decorator

The article lets you thoroughly understand the Python decorator principle, from this interview work no longer afraid.

First, the decoration device

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

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 parameter Func equivalent to Fdef outer (func):                    # defines a outer function as the adorner    def inner (): # If The steps of the inner () function are as follows: Print        (' start ')              # 1, first printed character ' start ',        R=func ()                    # 2, execute func function, Func function equivalent to Def f (): Print (' Medium ')         Print (' End ')                # 3, then the function prints ' end '        return r                    # 4, returns the result of the Func function return    inner@outerdef f ():              # F=outer (f) =innner    print (' Medium ') f ()                   # f () is equivalent to inner (), and the steps to perform the inner function look at the comment above the definition
#打印结果顺序为 start in end
2. Adorner 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

#其实只要将上面一种不带参数的装饰器修改一下就可以了 # Modification is also very simple, just change the parameters of inner and Func to (*args,**kwargs) #其他实现的过程和上面一种一样, no longer describes 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)          # f (1,4) equivalent to inner (1,4) The result printed here is the start 5 end
3, use of two decorative device

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 inner2def outer1 (func1): def inner1 (*args,**kwargs): Print (' Start ') r=func1 (*args, **kwargs) print (' End ') return R return Inner1@outer2 # here is equivalent to performing the 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,def f (): # At this time func1 is f ():p rint (' F function ') print (' F function ') #2, F=outer2 (f) similar f=outer2 (Inner1) F is                                                                         The return value of Outer2 is re-assigned to Inner2 # Func2 for inner1 function Inner1 inside func1 function for original F ():p rint (' F function ') F () # equivalent to executing oute                                R2 (Inner1) () >> start # Execute in outer function, first print ' Start ' >>start # execution Func2 is executed Inner1The function prints the ' start ' >>f function # in the Inner1 function func1 the f () function, printing the ' F function ' >>end # f function finished, then execute the INNER1 function inside the print (' End ') >> End # Finally execute the INNER2 function inside the print ( ' End ')
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 functoolsdef log (k= "):                                      #这里参数定义的是一个默认参数, if there is no incoming parameter, default is empty, 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__)        # above the adorner if there is no @functools.wraps (func), the function printed here is called Wrapper@log (' Excute ')                # fun2=log (' Excute ') (fun2) adorner using the given parameters Def fun2 (a):    print (A +) fun2 (10)

  

  

Python full stack development 8, decorator detailed

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.