Python Learning: 10.Python decorator Tutorial (i)

Source: Internet
Author: User
Tags function definition python decorator

Scenario Introduction

One day, when you're working overtime, the boss gives you the task of starting all the functions in this code to output a ' hello ' to the last output of the current time, and then output an "end", the code contains a lot of functions, what would you do?

defF1 ():Print('Proces a')        defF2 ():Print('Proces b')        deff3 ():Print('proces c')        deff4 ():Print('Proces D')......

Just getting this task, we might want to do this by adding a corresponding output statement to each function so that the task can be completed.

ImportdatetimedefF1 ():Print('Hello')    Print('Proces a')    Print('Datetime.datetime.now ()')    Print('End')defF2 ():Print('Hello')    Print('Proces b')    Print('Datetime.datetime.now ()')    Print('End')deff3 ():Print('Hello')    Print('proces c')    Print('Datetime.datetime.now ()')    Print('End')deff4 ():Print('Hello')    Print('Proces D')    Print('Datetime.datetime.now ()')    Print('End')......

By the time we implemented it, we found that it was too cumbersome, and each function was added at the end, so we thought of another way to write a function that was added to each function.

ImportdatetimedefHel ():Print('Hello')    Print(Datetime.datetime.now ())Print('End')defF1 ():Print('Hello')    Print('Proces a') Hel ()defF2 ():Print('Hello')    Print('Proces b') Hel ()deff3 ():Print('Hello')    Print('proces c') Hel ()deff4 ():Print('Hello')    Print('Proces D') Hel () ...

But we found that the hello in the beginning of the output is to be added in each function, it is still troublesome, in order to solve this problem, we need to talk about adorners.

Decorator Introduction

An adorner is essentially a Python function that allows other functions to add extra functionality without any code changes, and the return value of the adorner is also a function object. It is often used in scenarios where there is a need for facets, such as inserting logs, performance testing, transaction processing, caching, permission checking, and so on. Adorners are a great design for solving such problems, and with adorners, we can pull out a lot of similar code that is not related to the function itself and continue to reuse it. In summary, the function of an adorner is to add additional functionality to an already existing object.

Simple decorator

will start the problem to use the adorner to solve.

ImportdatetimedefHel (func):definner ():Print('Hello') R=func ()Print(Datetime.datetime.now ())Print('End')        returnRreturnInner@heldefF1 ():Print('Proces a') @heldefF2 ():Print('Proces b') @heldeff3 ():Print('proces c') @heldeff4 ():Print('Proces D') F1 () F2 () F3 () F4 () execution result: Helloproces a2018-06-24 18:03:21.903651endhelloproces b2018-06-24 18:03:21.915651endhelloproces C2018-06-24 18:03:21.915651endhelloproces D2018-06-24 18:03:21.915651End

It is not easy to use an adorner relative to the previous wording.

parse for the above code:

The adorner symbol "@" belongs to the syntactic sugar, the @ modifier must appear before the function definition line, the name of the following function as an argument, and the function is not allowed to be defined on the same line.

In the above code, Func refers to the F1, F2, F3, F4 functions, F1 as an example, the F1 function as a parameter into the HEL function, in the HEL function to define a inner () function, in the inner function, first execute a print (' Hello '), In the execution of the F1 function to assign the return value to R, the next output time and end, and finally return the last return of the R,inner function inner function, when we execute the F1 function, it is equivalent to execute the inner function, and can get the F1 function return value.

Passing parameters using adorners

In the adorner used above, the passed function has no parameters, when the function needs to be decorated with parameters, we will add the corresponding parameters in the adorner inner function, in the inner function called the Func function, again passed in.

defHel (func):defInner (name): R=func (name)Print('Bye')        returnRreturnInner@heldefF1 (name):Print('Hello')    Print(name) name='Alexsel'F1 (name) output result: Helloalexselbye

Although this solves the problem of the parameter, but the parameter we passed this time is just a string, if it is more complex parameter what to do, we can use some of our previous learning functions to receive a number of types of parameters, *args,**kwargs, After using these two parameters we can receive any type of parameter.

defHel (func):defInner (*args,**Kwargs): R= Func (*args,**Kwargs)Print('Bye')        returnRreturnInner@heldefF1 (name):Print('Hello')    Print(name) name='Alexsel'F1 (name) output result: Helloalexselbye

Here, the simple decorator is finished, the adorner has more advanced usage, next, the Decorator II will continue to explain to you the adorner.

Python Learning: 10.Python decorator Tutorial (i)

Related Article

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.