A deep understanding of Python decorators and a deep understanding of python decorations

Source: Internet
Author: User
Tags python decorator

A deep understanding of Python decorators and a deep understanding of python decorations

Decorator introduction:

Decorator is an advanced Python syntax. The decorator Can process a function, method, or class. In Python, we have multiple methods to process functions and classes. For example, in the Python closure, we can see the function object as the return result of a function. Compared with other methods, the decorator has simple syntax and high code readability. Therefore, the decorator is widely used in Python projects.

The decorator first appeared in Python 2.5. It was initially used for callable objects such as processing functions and methods (such as the _ call _ method ). In Python 2.6 and later versions, the decorator is further used for processing classes.

The decorator is mainly used to wrap functions. For some common functions, such as log printing, function timing, and identity authentication. We can use the decorator to reduce the complexity of the entire program and reduce the amount of code.

It is actually a function. The difference is that it treats a function as a parameter and returns an alternative function.

The following is a simple example:

def add_number(func):def adder(arg):return func(arg)+100return adderdef f(x):return xf=add_number(f)print f(20)

Add_number is a modifier function. It accepts a function (f) as a parameter and returns another function (adder) to assign a value to the original function. In this way, the original function implements the addition function without adding additional code.

This is the original implementation of the decorator.

But, this method is a little inconvenient. After all, it is still a circle, and f = add_number (f) is used to re-assign values to the original function.

In Python, you can use the following methods to simplify the reference of the decorator.

def add_number(func):def adder(arg):return func(arg)+100return adder@add_numberdef f(x):return xprint f(20)

You only need a simple @ add_numbe call, which is much simpler than the original code.

No. As a decoration device, there are only two parameters accepted each time: function and function parameters. However, the writing format is basically the same. Is there a way to simplify this writing?

Yes. Python provides a decorator package, which greatly simplifies the writing of the decorator.

So, the third implementation method is:

from decorator import decorator@decoratordef wrapper(func,arg):return func(arg)+100@wrapperdef f(x):return xprint f(20)

Oh, it's actually easier ~

In the preceding example, all parameters are accepted. In fact, the function itself can accept variable parameters.

For example:

@decoratordef wrapper(f,arg1,*args,**kwargs):print "I am just a wrapper~"return f(arg1,*args,**kwargs)@wrapperdef f(arg1,*args,**kwargs):print arg1for eacheArg in args:print 'non-keyword arg:',eacheArgfor eachKw in kwargs.keys():print 'keyword arg: %s:%d' % (eachKw,kwargs[eachKw])args=('Joy','Steve')kwargs={"age":20}f('China',*args,**kwargs)

Output result:

I am just a wrapper~Chinanon-keyword arg: Joynon-keyword arg: Stevekeyword arg: age:20

For the difference between * args and ** kwargs, both of them can be used to represent variable-length parameters. However, the former is represented by the ancestor without a key value, while the latter is a dictionary with a key value. The two can be used in the same function. However, * args must appear before ** kwargs.

For example:

def test_var_args_call(arg1, arg2, arg3):print "arg1:", arg1print "arg2:", arg2print "arg3:", arg3args=(1,2,3)kwargs ={"arg1":"1","arg3": 3, "arg2": "2"}test_var_args_call(*args)print '-----------------'test_var_args_call(**kwargs)

The two achieve the same effect.

The last example is to describe a function by displaying the execution time of the function.

import timedef log(func):def wrapper(*args, **kw):print '[%s] %s() was called...' % (time.ctime(),func.__name__)return func(*args, **kw)return wrapper@logdef foo():passfor i in range(4):foo()time.sleep(1)

The output result is as follows:

[Wed Jul 27 09:17:23 2016] foo() was called...[Wed Jul 27 09:17:24 2016] foo() was called...[Wed Jul 27 09:17:25 2016] foo() was called...[Wed Jul 27 09:17:26 2016] foo() was called...

The above is an in-depth understanding of the Python decorator introduced by the small editor. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.