Decorator usages in Python _python

Source: Internet
Author: User

I've already covered the decorator in my previous blog about Python 2.4 features, but then it was suit and now I'm going to describe it in detail.

A detailed introduction to decorator is already in the What ' s new in Python 2.4, and you can take a look.

How to call Decorator

Basically there are two forms of calling decorator

First type:

Copy Code code as follows:

@a
def f ():

This form is decorator with no parameters. Eventually Python will process it as:

Copy Code code as follows:

f = A (f)

You can also expand to:
Copy Code code as follows:

@a
@B
@c
def f ():

Eventually Python will process it as:

Copy Code code as follows:

f = A (B (C (f)))

Note: The document is written in the form of @a @B @c, but in fact it is not possible to write more than one line. And the order of execution comes in the order of function calls, first the bottom C, then B, then A. Therefore, if the decorator has the order, must note: First to perform the bottom, the last execution on the top. (there should be no such reverse relationship)

The second type:

Copy Code code as follows:

@a (args)
def f ():

This form is the decorator with the parameters of the formulation. Then Python will handle it as:

Copy Code code as follows:

def f ():
_deco = A (args)
f = _deco (f)

As you can see, Python first executes a (args) to get a decorator function and then processes it in the same way as the first.

Definition of decorator function

Each decorator should have a corresponding function, it should be processed on the following functions, either return the original function object, or return a new function object. Note that decorator is only used to handle functions and class methods.

First type:
the needle for the first invocation of the form

Copy Code code as follows:

def A (func):
#处理func
#如func. attr= ' decorated '
return func
@a
def f (args):p

After the Func is processed, the original function object is still returned. The argument for this decorator function is the function to be processed. If you want to return a new function, you can:

Copy Code code as follows:

def A (func):
def new_func (args):
#做一些额外的工作
return func (args) #调用原函数继续进行处理
Return New_func
@a
def f (args):p

Note that New_func is defined in the same way as the function to be processed, so it can be written in general, such as:

Copy Code code as follows:

def A (func):
def new_func (*args, **argkw):
#做一些额外的工作
return func (*args, **argkw) #调用原函数继续进行处理
Return New_func
@a
def f (args):p

As you can see, a new function is defined in a and then a returns the new function. In the new function, take care of something, such as checking the parameters, or doing some other work, and then adjusting the original function for processing. This pattern can be seen as a way of doing some processing before calling a function by using the decorator technique before calling the function. If you want to do some processing after calling the function, or further, after calling the function, some processing can be done based on the return value of the function:

Copy Code code as follows:

def A (func):
def new_func (*args, **argkw):
result = Func (*args, **argkw) #调用原函数继续进行处理
If result:
#做一些额外的工作
Return New_result
Else
return result
Return New_func
@a
def f (args):p

The second type:
for the second form of invocation

On the document, if your decorator uses arguments in the call, your decorator function will only use these parameters to invoke, so you need to return a new decorator function, which is consistent with the first form.

Copy Code code as follows:

def A (ARG):
def _a (func):
def new_func (args):
#做一些额外的工作
return func (args)
Return New_func
Return _a
@a (ARG)
def f (args):p

You can see that a (ARG) returns to a new decorator _a.

Decorator's application scenario

But I've been thinking, what exactly is decorator's magic? What are the appropriate occasions? Do I need to use it?

The magic of decorator is that it can process the modified function. This process is done without altering the original function code. Kind of like I know a little bit about AOP (aspect-oriented programming) idea.

It fits the occasion I can think of enumerating out the following:

1. As stated in the document, it was originally designed to make it easier to invoke Staticmethod and Classmethod
2. Do some work before some functions are executed, such as web development, and many functions need to check to see if the user is logged in before calling
3. Do some work after the function is performed, such as after the call is completed, write the log according to the return status
4. Do parameter check

There may be many more, you can freely play the imagination

So do I need to use it?

I think it depends on you. However, I think in some cases, using decorator can increase the flexibility of the program and reduce the degree of coupling. For example, the previous user login check. It's true that you can write a generic login check function and then call it in each function. But this creates a function that is inflexible and increases the degree of integration with other functions. If the user login check function changes, such as the return value of the judgment has changed, it is possible that every function to use it to modify. The use of decorator does not cause this problem. The use of Decorator syntax also makes the code simple and clear (once you are familiar with its syntax). Of course you do not use it is possible. However, the combination of this function is more in line with the requirements of building blocks, it can be further decomposition of function functions, so that the function is simple enough and single. And then through the decorator mechanism of flexible to string related functions into a string, it is really good to think. Like the following:

Copy Code code as follows:

@a
@B
def account (args):p

Assuming that this is an accounting processing function, account accounts. But a real accounting there are some judgments and processing, such as: B Check account status, a log. This effect is actually to check B, through the processing in a can first execute account, and then log processing. As easy as building blocks, it's easy to change them. You can even write account as decorator, and the following function is an empty function. Then through the configuration file and other methods, the combination of decorator to save, the basic realization of the function of the Assembly. is not very ideal.

The creativity that Python brings to people is really infinite!

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.