Python Decorator Learning Notes

Source: Internet
Author: User


The adorner was first presented in Python 2.5, and it was originally used for processing functions and methods such as callable objects (callable object, which are defined as __call__ methods). In Python 2.6 and later Python versions, adorners are further used to process classes.

This is found in many places:

@app. Route ('/')
Def hello_world ():
Return ' Hello world! '

Call the function before adding a @ What the hell, it turns out to be using a python decorator. Write a simple Python adorner sample based on the online tutorials:


# Coding=utf-8

# define an Adorner
def mydecorator (func):
def wrapper (*ARGS,**KW):
Print (' Hi,now is: ')
return func (*ARGS,**KW)
Return wrapper

# Use Adorners
@mydecorator
def now ():
Print (' 2015-12-9 ')

Now ()

Run Result:

D:\learn-python>python decorator.py
Hi,now is:
2015-12-9

Add the @mydecorator adorner before the now function, which automatically prints a line of information in front of the

Add:

Because a function is also an object, and a function object can be assigned to a variable, the function can also be called through a variable.

>>> def now ():
... print ' 2013-12-25 '
...
>>> F = Now
>>> F ()
2013-12-25
The function object has a __name__ property that can get the name of the function:

>>> now.__name__
' Now '
>>> f.__name__
' Now '
Now, let's say we're going to enhance the functionality of the current () function, such as automatically printing logs before and after a function call, but not the definition of the present () function, which dynamically adds functionality during code runs, and is called an "adorner" (decorator).

In essence, decorator is a higher order function that returns a function. So, we want to define a decorator that can print the log, which can be defined as follows:

def log (func):
def wrapper (*args, **kw):
print ' Call%s (): '% func.__name__
return func (*args, **kw)
Return wrapper
Look at the log above, because it is a decorator, so take a function as an argument and return a function. We're going to use Python's @ syntax to place decorator at the definition of the function:

@log
def now ():
print ' 2013-12-25 '
Calling the now () function will not only run the now () function itself, but will also print a row of logs before running the Now () function:

>>> Now ()
Call Now ():
2013-12-25
Place the @log at the definition of the now () function, which is equivalent to executing the statement:

now = log (now)
Since log () is a decorator, returns a function, so the original now () function still exists, but the current variable with the same name today points to the new function, and then the call is to execute the new function, that is, the wrapper () function returned in the log () function.

The parameter definition for the wrapper () function is (*args, **kw), so the wrapper () function can accept calls of any parameter. Within the wrapper () function, the log is printed first, followed by the call to the original function.

If the decorator itself needs to pass in parameters, then it is more complicated to write a higher order function that returns decorator. For example, to customize the log text:

def log (text):
def decorator (func):
def wrapper (*args, **kw):
Print '%s%s (): '% (text, func.__name__)
return func (*args, **kw)
Return wrapper
return decorator
This 3-layer nested decorator usage is as follows:

@log (' Execute ')
def now ():
print ' 2013-12-25 '
The results of the implementation are as follows:

>>> Now ()
Execute Now ():
2013-12-25
Compared to the two-layer nested decorator, the 3-layer nesting effect is this:

>>> now = log ("Execute") (now)
Let's dissect the above statement, first execute log (' Execute '), return the Decorator function, call the returned function, the argument is the now function, and the return value is the wrapper function.

Both of the above definitions of decorator are fine, but the final step is not. Because we're talking about functions as objects, it has attributes like __name__, but you go to see the functions after decorator, their __name__ has changed from the original ' now ' to ' wrapper ':

>>> now.__name__
' Wrapper '
Because the return of the wrapper () function name is ' wrapper ', you need to copy the original function __name__ and other attributes into the wrapper () function, otherwise, some dependent function signature code execution will be wrong.

There is no need to write wrapper.__name__ = func.__name__ Such code, Python built-in functools.wraps is doing this, so a complete decorator is written as follows:

Import Functools

def log (func):
@functools. Wraps (func)
def wrapper (*args, **kw):
print ' Call%s (): '% func.__name__
return func (*args, **kw)
Return wrapper
or for decorator with parameters:

Import Functools

def log (text):
def decorator (func):
@functools. Wraps (func)
def wrapper (*args, **kw):
Print '%s%s (): '% (text, func.__name__)
return func (*args, **kw)
Return wrapper
return decorator
Import Functools is a functools module. The concept of a module is explained later. Now just remember to add @functools.wraps (func) to the front of the definition wrapper ().

Summary

In object-oriented (OOP) Design patterns, decorator is called a decorative pattern. OOP's decorative patterns need to be implemented through inheritance and combination, and Python supports decorator directly from the grammar level in addition to the OOP decorator. Python's decorator can be implemented using functions or classes.

Decorator can enhance function, although it is a bit complicated to define, it is very flexible and convenient to use.

Write a decorator that prints a log of ' Begin call ' and ' end called ' before and after the function calls.

Think again about whether you can write a @log decorator that supports both:

@log
def f ():
Pass
also supports:

@log (' Execute ')
def f ():
Pass

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.