Home > Backend Development > Python Tutorial > Python decorator details

Python decorator details

Release: 2020-06-19 17:11:51
forward
1849 people have browsed it

A decorator is essentially a Python function, which allows other functions to add additional functions without making any code changes. The return value of the decorator is also a function object.

Python decorator details

is often used in scenarios with cross-cutting requirements, such as: log insertion, performance testing, transaction processing, caching, permission verification, etc. Decorators are an excellent design to solve this kind of problem. With decorators, we can extract a large amount of similar code that has nothing to do with the function itself and continue to reuse it.

Let’s take a look at a simple example first:

def now():
    print('2017_7_29')
Copy after login

Now there is a new requirement. I hope to record the execution log of the function, so I add the log code to the code:

def now():
    print('2017_7_29')
    logging.warn("running")
Copy after login

Suppose there are multiple similar requirements, how to do it? Write another record in the now function? This results in a lot of similar code. In order to reduce repeated code writing, we can redefine a function: specifically process the log, and then execute the real business code after the log is processed.

def use_logging(func):     
    logging.warn("%s is running" % func.__name__)     
    func()  
def now():     
    print('2017_7_29')    
use_logging(now)
Copy after login

In Implementation, is not difficult logically, but in this case, we have to pass a function as a parameter to the log function every time. Moreover, this method has destroyed the original code logical structure. When executing business logic before, now() was executed, but now it has to be changed to use_logging(now).

So is there a better way? Of course there is, the answer is decorators.

First of all, you must understand that a function is also an object, and function objects can be assigned to variables, so the function can also be called through variables. For example:

(=
Copy after login

Simple decorator

Essentially, decorator is a higher-order function that returns a function. Therefore, we need to define a decorator that can print logs, which can be defined as follows:

def log(func):
    def wrapper(*args,**kw):
        print('call %s():'%func.__name__)
        return func(*args,**kw)
    return wrapper
# 由于log()是一个decorator,返回一个函数,所以,原来的now()函数仍然存在,
# 只是现在同名的now变量指向了新的函数,于是调用now()将执行新函数,即在log()函数中返回的wrapper()函数。
# wrapper()函数的参数定义是(*args, **kw),因此,wrapper()函数可以接受任意参数的调用。
# 在wrapper()函数内,首先打印日志,再紧接着调用原始函数。
Copy after login

The above log, because it is a decorator, accepts a function as a parameter and returns a function .Now execute:

now = log(now)
now()
Copy after login
输出结果:
call now():
2017_7_28
Copy after login

Functionlog is the decorator. It wraps the func that executes the real business method in the function. It looks like now is decorated by log. In this example, when the function enters, it is called an aspect (Aspect), and this programming method is called aspect-oriented programming (Aspect-Oriented Programming).

Use syntactic sugar:

@logdef now():
    print('2017_7_28')
Copy after login

@The symbol is the syntactic sugar of the decorator. It is used when defining a function to avoid another assignment operation

In this way we You can omit the sentence now = log(now), and directly call now() to get the desired result. If we have other similar functions, we can continue to call the decorator to decorate the function without repeatedly modifying the function or adding new packages. In this way, we improve the reusability of the program and increase the readability of the program.

The reason why decorators are so convenient to use in Python is that Python functions can be passed as parameters to other functions like ordinary objects, can be assigned to other variables, and can be used as return values. Can be defined within another function.

Decorator with parameters:

If the decorator itself needs to pass in parameters, then you need to write a high value that returns the decorator Order functions are a bit more complicated to write. For example, to customize the text of the log:

def log(text):
    def decorator(func):
            def wrapper(*args,**kw):
                        print('%s %s()'%(text,func.__name__))
                        return func(*args,**kw)        
            return wrapper    
     return decorator
Copy after login

The usage of this 3-layer nested decorator is as follows:

@log(()
now()
Copy after login

is equivalent to

<span style="color: #000000;">now = log('goal')(now)<br># 首先执行log('execute'),返回的是decorator函数,再调用返回的函数,参数是now函数,返回值最终是wrapper函数<br>now()</span>
Copy after login

because we have said that functions are also objects. , it has attributes such as __name__, but if you look at the functions decorated by decorator, their __name__ has changed from the original 'now' to 'wrapper':

print(now.__name__)# wrapper
Copy after login

Because the returned wrapper() function name is 'wrapper', so you need to change the # of the original function ##__name__ and other attributes are copied to the wrapper() function, otherwise, some codes that rely on function signatures will execute incorrectly.

There is no need to write code like

wrapper.__name__ = func.__name__, Python’s built-in functools.wraps does this, so it is a complete decorator The writing method is 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
Copy after login
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
Copy after login

Class decorator:

Let’s look at the class decorator again. Compared with the function decorator, the class decorator has greater flexibility and high content. Polymerization, encapsulation and other advantages. Using class decorators can also rely on the __call__ method inside the class. When the @ form is used to attach the decorator to a function, this method will be called.

import time

class Foo(object):     
    def __init__(self, func):     
        self._func = func  
    
    def __call__(self):     
        print ('class decorator runing')     
        self._func()     
        print ('class decorator ending')  

@Foo 
def now():     
    print (time.strftime('%Y-%m-%d',time.localtime(time.time())))  
    
now()
Copy after login
Summary:

Summary In other words, the purpose of a decorator is to add additional functionality to an existing object.

At the same time, in the object-oriented (OOP) design mode, decorator is called the decoration mode. OOP's decoration mode needs to be implemented through inheritance and combination, and Python, in addition to supporting OOP's decorator, also supports decorators directly from the syntax level. Python's decorator can be implemented as a function or a class.

For more related knowledge, please pay attention to python video tutorial column

The above is the detailed content of Python decorator details. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template