search

Python decorator details

Jun 18, 2020 pm 05:40 PM
pythonDecorator

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')

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")

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)

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:

(=

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()函数内,首先打印日志,再紧接着调用原始函数。

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

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

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')

@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

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

@log(()
now()

is equivalent to

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

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

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
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

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()
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
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 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.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!