Home Backend Development Python Tutorial Python decorator details

Python decorator details

Jun 18, 2020 pm 05:40 PM
python Decorator

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles