How to use decorator functions in Python

PHPz
Release: 2023-10-19 09:10:48
Original
1239 people have browsed it

How to use decorator functions in Python

How to use the decorator function in Python

In Python programming, decorators (decorators) are a very useful tool. It allows us to extend the function with additional functionality without modifying the original function code. Decorator functions can automatically perform some operations before and after function execution, such as logging, timing, verifying permissions, etc. This article will introduce the basic concepts of decorator functions and provide some concrete code examples.

1. Definition of decorator function

A decorator function is a function that accepts a function as a parameter and returns a new function. It can be applied to functions using @ syntax. The following is an example of a simple decorator function definition:

def decorator_function(original_function):
    def wrapper_function(*args, **kwargs):
        # 在函数执行前的操作
        print("Before executing the function")
        # 执行原始函数
        result = original_function(*args, **kwargs)
        # 在函数执行后的操作
        print("After executing the function")
        return result
    return wrapper_function
Copy after login

2. Application of decorator function

The decorator function can perform some additional operations before and after the function is executed. The following is an example of using a decorator function to implement timing functions:

import time

def timer_decorator(original_function):
    def wrapper_function(*args, **kwargs):
        start_time = time.time()
        result = original_function(*args, **kwargs)
        end_time = time.time()
        execution_time = end_time - start_time
        print(f"Execution time: {execution_time} seconds")
        return result
    return wrapper_function

@timer_decorator
def my_function():
    time.sleep(1)
    print("Function executed")

my_function()
Copy after login

In the above example, the timer_decorator decorator function is applied to the my_function function. When my_function is called, the decorator records the start time before the function is executed, calculates the end time after the function is executed, and calculates the execution time of the function.

3. Parameters of the decorator function

The decorator function can accept parameters to apply different decorators to different functions. The following is an example of a decorator function with parameters:

def prefix_decorator(prefix):
    def decorator_function(original_function):
        def wrapper_function(*args, **kwargs):
            print(f"{prefix}: Before executing the function")
            result = original_function(*args, **kwargs)
            print(f"{prefix}: After executing the function")
            return result
        return wrapper_function
    return decorator_function

@prefix_decorator("LOG")
def my_function():
    print("Function executed")

my_function()
Copy after login

In the above example, the prefix_decorator function returns a decorator function that prints log information with the prefix before and after the function is executed.

4. Application of multiple decorators

You can apply multiple decorator functions to the same function to form a stacking effect of decorators. Here is an example of applying multiple decorators:

def decorator1(original_function):
    def wrapper_function(*args, **kwargs):
        print("Decorator 1: Before executing the function")
        result = original_function(*args, **kwargs)
        print("Decorator 1: After executing the function")
        return result
    return wrapper_function

def decorator2(original_function):
    def wrapper_function(*args, **kwargs):
        print("Decorator 2: Before executing the function")
        result = original_function(*args, **kwargs)
        print("Decorator 2: After executing the function")
        return result
    return wrapper_function

@decorator1
@decorator2
def my_function():
    print("Function executed")

my_function()
Copy after login

In the above example, the decorator1 and decorator2 decorator functions are applied to the my_function function in sequence. When my_function is called, decorator 2 will be executed after decorator 1.

Summary:

The decorator function is a very useful tool in Python, which can extend the function with additional functions without modifying the original function code. By providing some concrete code examples, this article hopes to help readers understand the basic concepts of decorator functions and how to use them. Using decorator functions reduces code duplication and makes the code more modular and easier to maintain.

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

Related labels:
source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!