Python Full stack development

Source: Internet
Author: User

Python Full stack development

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:

12345678910111213141516 # 使用@语法放在函数的定义上面 相当于执行 f=outer(f),此时f赋值成为了一个新的outer函数,# 此时f函数就指向了outer函数的返回值inner,inner是一个函数名,定义在oute函数里面# 原来的f是函数名可简单理解为一个变量,作为outer函数的参数传递进去了 此时参数func相当于fdefouter(func):                    # 定义一个outer函数作为装饰器    definner():            # 如果执行inner()函数的话步骤如下:        print(‘start‘)              # 1、首先打印了字符‘start’,        r=func()                    # 2、执行func函数,func函数相当于def f(): print(‘中‘)        print(‘end‘)                # 3、接着函数打印‘end’        return r                    # 4、将func函数的结果返回    returninner@outerdeff():              # f=outer(f)=innner    print(‘中‘)f()                   # f()相当于inner(),执行inner函数的步骤看上面定义处的注释<br>#打印结果顺序为   start 中 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

123456789101112131415 #其实只要将上面一种不带参数的装饰器修改一下就可以了#修改也很简单,只需将inner和func的参数改为 (*args,**kwargs)#其他实现的过程和上面一种一样,就不再介绍了defouter(func):    definner(*args,**kwargs):        print(‘start‘)        r=func(*args,**kwargs)    # 这里func(*args,**kwargs)相当于f(a,b)        print(‘end‘)        returnr    returninner@outerdeff(a,b):    print(a+b)f(1,4)                    # f(1,4)相当于inner(1,4) 这里打印的结果为 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.

12345678910111213141516171819202122232425262728 defouter2(func2):    definner2(*args,**kwargs):        print(‘开始‘)        r=func2(*args,**kwargs)        print(‘结束‘)        returnr    returninner2defouter1(func1):    definner1(*args,**kwargs):        print(‘start‘)        r=func1(*args,**kwargs)        print(‘end‘)        returnr    returninner1@outer2 # 这里相当于执行了 f=outer1(f)  f=outer2(f),步骤如下@outer1#1、f=outer1(f) f被重新赋值为outer1(1)的返回值inner1,deff():                               #    此时func1为 f():print(‘f 函数‘)    print(‘f 函数‘)                     #2、f=outer2(f) 类似f=outer2(inner1) f被重新赋值为outer2的返回值inner2                                       #    此时func2 为inner1函数 inner1里面func1函数为原来的 f():print(‘f 函数‘)                                                                         f()                                    # 相当于执行 outer2(inner1)()>>开始                                  # 在outer函数里面执行,首先打印 ‘开始 ’>>start                                # 执行func2 即执行inner1函数 打印 ‘start’>>f 函数                               # 在inner1函数里面执行 func1 即f()函数,打印 ‘f 函数’>>end                                  # f函数执行完,接着执行inner1函数里面的 print(‘end‘)>>结束                                 # 最后执行inner2函数里面的 print(‘结束‘)
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-

12345678910111213141516171819202122232425 import functoolsdeflog(k=‘‘):                                        #这里参数定义的是一个默认参数,如果没有传入参数,默认为空,可以换成其他类型的参数    defdecorator(func):        @functools.wraps(func)                        #这一句的功能是使被装饰器装饰的函数的函数名不被改变,        defwrapper(*args, **kwargs):            print(‘start‘)            print(‘{}:{}‘.format(k, func.__name__))    #这里使用了装饰器的参数k            r =func(*args, **kwargs)            print(‘end‘)            returnr        return wrapper    returndecorator@log()                        # fun1=log()(fun1) 装饰器没有使用参数deffun1(a):    print(a + 10)fun1(10)# print(fun1.__name__)        # 上面装饰器如果没有@functools.wraps(func)一句的话,这里打印出的函数名为wrapper@log(‘excute‘)                # fun2=log(‘excute‘)(fun2) 装饰器使用给定参数deffun2(a):    print(a +20)fun2(10)

  

Python Full stack development

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.