Python decorator, one is enough (get materials below)

Decorators are an important part of Python. Simply put: they are functions that modify the functions of other functions. It helps to make our code shorter and more python. Many Python users don't know where to use them and where decorators can make the code more concise. Through the study of this article, you can understand and learn the decorator, and make you more Python! Come and study together.

1. Definition of decorator

It is a function that adds additional functions to existing functions. It is essentially a closure function. Functional features of decorator:

1. Do not modify the source code of existing functions

2. Do not modify the calling method of existing functions

3. Add additional functions to existing functions

4. Distinction between closures and decorators:

If a closure function has only one parameter and is a function type, the closure function is called a decorator. Writing code should follow the open and closed principle, which stipulates that the implemented function code is not allowed to be modified, but can be extended.

2. Example code of decorator

# Define decorator
def decorator(func):
    def inner():
        # Decorate existing functions in internal functions
        print('Login authentication added')
        func()
    return inner

def comment():
    print('Comment')
# Call the decorator to decorate the existing function. comment=inner on the left
comment = decorator(comment)
# The calling method remains unchanged
comment()

3. Grammar of ornament

If multiple functions need to add login verification function, you need to write func = decorator(func) code every time to decorate the existing functions. This method is still troublesome.

Python provides a simpler way to write decorative functions, that is, syntax sugar. The writing format of syntax sugar is: @ decorator name. You can also decorate existing functions through syntax sugar.

# Define decorator
def decorator(func):
    def inner():
        # Decorate existing functions in internal functions
        print('Login authentication added')
        func()
    return inner

@decorator  # The comment = decorator(comment) decorator syntax encapsulates the code. comment=inner on the left
def comment():
    print('Comment')
# The calling method remains unchanged
comment()

4. Timing of decorator execution

After the current module is loaded, the decorator will execute immediately to decorate the existing functions.

# Define decorator
def decorator(func):
    print('The decorator has been executed')
    def inner():
        # Decorate existing functions in internal functions
        print('Login authentication added')
        func()
    return inner

@decorator  # The comment = decorator(comment) decorator syntax encapsulates the code. comment=inner on the left
def comment():
    print('Comment')

5. Use of decorator

5.1 use scenario of decorator

1.Statistics of function execution time.

2.Output log information.

5.2 statistics of execution time of existing functions implemented by decorator

import time

def decorator(func):
    def inner():
        # Get the time difference from 1970-1-1 0:0:1
        begin = time.time()
        func()
        end = time.time()
        result = end - begin
        print(f'Function execution completion time:{result}')
    return inner

@decorator
def work():
    for i in range(10000):
        print(i)
        
work()

6. Use of universal decorator

Universal decorator: can decorate any type of function. When decorating an existing function with a decorator, the type of the inner function is consistent with the type of the existing function to be decorated.

6.1 decorating functions with parameters

def decorator(func):
    def inner(num1, num2):
        print('Trying to perform an addition calculation')
        func(num1, num2)
    return inner

@decorator
def add_num(num1, num2):
    result = num1 + num2
    print(f'The result is:{result}')

add_num(1, 2)

6.2 decorating functions with parameters and return values

def decorator(func):
    def inner(num1, num2):
        print('Trying to perform an addition calculation')
        num = func(num1, num2)
        return num
    return inner

@decorator
def add_num(num1, num2):
    result = num1 + num2
    return result

result = add_num(1, 2)
print(f'The result is:{result}')

6.3 decorating functions with indefinite length parameters and return values

def decorator(func):
    def inner(*args, **kwargs):
        print('Trying to perform an addition calculation')
        # *args: pass each element in the tuple as a positional parameter
        # **kwargs: pass each key value pair in the dictionary as a keyword
        num = func(*args, **kwargs)
        return num
    return inner

@decorator
def add_num(*args, **kwargs):
    result = 0
    for value in args:
        result += value
    for value in kwargs.values():
        result += value
    return result

result = add_num(1, 2, a=3)
print(f'The result is:{result}')

7. Use of multiple decorators

Decoration process of multiple decorators: a decoration process from inside to outside. First execute the internal decorator and then the external decorator.

def make_div(func):
    print('make_div The decorator has been executed')

    def inner():
        result = '<div>' + func() + '</div>'
        return result
    return inner

def make_p(func):
    print('make_p The decorator has been executed')

    def inner():
        result = '<p>' + func() + '</p>'
        return result
    return inner
# Principle analysis: content = make_div(make_p(content))
# Distribution: content = make_p(content), interior decorator completed, content = make_p.inner
#          content = make_div(make_p.inner)
@make_div
@make_p
def content():
    return 'Life is short, I use it python'

c = content()
print(c)



make_p The decorator has been executed

make_div The decorator has been executed

<div><p>Life is short, I use it python</p></div>

8. Decorator with parameters

Decorators with parameters can pass in specified parameters when decorating functions with decorators. Syntax format: @ decorators (parameters,...). Using a decorator with parameters actually wraps a function outside the decorator. The function receives parameters and returns the decorator, because the @ symbol needs to be used with the decorator instance.

def return_decorator(flag):
    # The decorator can only receive one parameter and is a function type
    def decorator(func):
        def inner(a, b):
            if flag == '+':
                print('Trying to perform an addition calculation')
            elif flag == '-':
                print('Efforts are being made to perform subtraction calculations')
            func(a, b)
        return inner
    # When the function is called, a decorator decorato can be returned
    return decorator

@return_decorator('+')  # decorator = return_decorator('+'), @decorator => add_num = decorator(add_num)
def add_num(a, b):
    result = a + b
    print(result)
    
@return_decorator('-')
def sub_num(a, b):
    result = a - b
    print(result)

add_num(1, 2)
sub_num(1, 2)

9. Use of class decorators

Class decorator: decorate existing functions with classes

class MyDecorator(object):
    def __init__(self, func):
        self.__func = func

    # Realize__ call__ Method, indicating that the object is a callable object and can be called like a function
    def __call__(self, *args, **kwargs):
        # Encapsulate existing functions
        print('We'll be off duty soon')
        self.__func()
@MyDecorator  # @MyDecorator => show = MyDecorator(show)
def show():
    print('It's going to snow')
# Executing show is equivalent to executing the instance object created by MyDecorator class. Show() = > object ()
show()



We'll be off duty soon

It's going to snow

Extension:

The function can be called because the call method is implemented inside the function.

10. Decorator application scenario

1. Collect operation or error logs for functions.

2. Verify the permission of the function.

3. Calculates the run time of the function.

4. During ORM/DB model operation, the associated data is dynamically obtained through attribute method.

5. Cache of function data.

6. Customize the input and output of functions (serialization and deserialization).

Original text from: https://blog.csdn.net/mall_lucy/article/details/108791699
Author: the South Branch is warm and the North Branch is cold

That's all for today's dry goods. Next, let's share a python interview document. The dry goods are full!
Click the link to get the complete document


※ some articles come from the Internet. If there is infringement, please contact to delete; More articles and materials | click the text directly behind ↓↓

100GPython self study package
Alibaba cloud K8s combat manual
Alibaba cloud CDN pit drainage guide
ECS operation and maintenance guide
DevOps Practice Manual
Hadoop big data Practice Manual
Knative cloud native application development guide
OSS operation and maintenance manual
Cloud native architecture white paper
Zabbix enterprise distributed monitoring system source code document
10G large factory interview questions

Keywords: Operation & Maintenance cloud computing

Added by nickmanners on Sat, 27 Nov 2021 02:56:36 +0200