[Learn python from zero] 32. The role of decorators (1)

decorator

Decorator is a function that is often used in program development. If you use decorators well, the development efficiency will be even more powerful, so this is also a must-ask question in Python interviews. But for many people who are new to this knowledge, this function is a bit confusing. They bypassed it directly during self-study, and then hung up when they were asked in the interview, because decorators are the basic knowledge of program development, and they don’t know this. Don’t tell others Say you know Python, read the following article to ensure that you learn decorators.

1. First understand this code

#### 第一波 ####
def foo():
    print('foo')

foo  # 表示是函数
foo()  # 表示执行foo函数

#### 第二波 ####
def foo():
    print('foo')

foo = lambda x: x + 1

foo()  # 执行lambda表达式,而不再是原来的foo函数,因为foo这个名字被重新指向了另外一个匿名函数

The function name is just a variable, it just points to the defined function, so it can be called through the function name (), if the function name = xxx is modified, then when the function name () is executed, the caller does not know the previous one function

2. The demand comes.
The start-up company has N business departments, and the basic platform department is responsible for providing the underlying functions, such as: database operation, redis call, monitoring API and other functions. When the business department uses the basic functions, it only needs to call the functions provided by the basic platform. as follows:

################ The functions provided by the basic platform are as follows ################

def f1():
    print('f1')

def f2():
    print('f2')

def f3():
    print('f3')

def f4():
    print('f4')

################ Business department A calls the functions provided by the basic platform ################

f1()
f2()
f3()
f4()

################ Business department B calls the functions provided by the basic platform ################

f1()
f2()
f3()
f4()

At present, the company is proceeding in an orderly manner. However, the developers of the previous basic platform did not pay attention to verification-related issues when writing code, that is, the functions provided by the basic platform can be used by anyone. Now it is necessary to refactor all the functions of the basic platform, and add a verification mechanism for all the functions provided by the platform, that is, verify before executing the function.

The boss handed over the work to Low B, and he did this:
Negotiate with each business department, each business department writes its own code, and verifies before calling the functions of the basic platform.

The boss handed over the work to Low B. Here's what he did:

Negotiate with each business department, each business department writes its own code, and verifies before calling the functions of the basic platform. Hey, so the base platform doesn't need to be modified in any way. It's great, I have plenty of time to pick up girls...

Low B was fired that day...

The boss gave the job to Low BB, here's how he did it:

############### 基础平台提供的功能如下 ############### 

def f1():
    # 验证1
    # 验证2
    # 验证3
    print('f1')

def f2():
    # 验证1
    # 验证2
    # 验证3
    print('f2')

def f3():
    # 验证1
    # 验证2
    # 验证3
    print('f3')

def f4():
    # 验证1
    # 验证2
    # 验证3
    print('f4')

############### 业务部门不变 ############### 
### 业务部门A 调用基础平台提供的功能### 

f1()
f2()
f3()
f4()

### 业务部门B 调用基础平台提供的功能 ### 

f1()
f2()
f3()
f4()

After a week, Low BB was fired...

The boss gave the job to the Low BBB, and here's how he did it:

Only the code of the basic platform is refactored, and other business departments do not need to make any changes

############### 基础平台提供的功能如下 ############### 

def check_login():
    # 验证1
    # 验证2
    # 验证3
    pass


def f1():

    check_login()

    print('f1')

def f2():

    check_login()

    print('f2')

def f3():

    check_login()

    print('f3')

def f4():

    check_login()

    print('f4')

The boss looked at the realization of the Low BBB, a gratified smile leaked from the corner of his mouth, and chatted with the Low BBB earnestly:

The boss said: When
writing code, you must follow the principle of openness and closure. Although this principle is used for object-oriented development, it is also applicable to functional programming. Simply put, it stipulates that the implemented functional code is not allowed to be modified, but it can be extended. ,Right now:

Closed: Function code blocks that have been implemented
Open: If the principle of openness and closure is applied to the above requirements for extended development
, then it is not allowed to modify the code inside the functions f1, f2, f3, and f4, and the boss gave Low BBB a Implementation plan:

def w1(func):
    def inner():
        # 验证1
        # 验证2
        # 验证3
        func()
    return inner

@w1
def f1():
    print('f1')

@w1
def f2():
    print('f2')

@w1
def f3():
    print('f3')

@w1
def f4():
    print('f4')

For the above code, only by modifying the code of the basic platform, [Verify] can be performed before other people call functions f1, f2, f3, and f4, and other business departments do not need to do anything.

Low BBB asked in horror, what is the internal execution principle of this code?

The boss was about to get angry, when suddenly Low BBB's phone fell to the ground, and it happened that the screensaver was the photo of Low BBB's girlfriend.

Started to explain in detail:

Take f1 alone as an example:

def w1(func):
    def inner():
        # 验证1
        # 验证2
        # 验证3
        func()
    return inner

@w1
def f1():
    print('f1')

The python interpreter will interpret the code from top to bottom, the steps are as follows:

def w1(func):  # 将w1函数加载到内存
@w1  # 从表面上看解释器仅仅会解释这两句代码,因为函数在没有被调用之前其内部代码不会被执行。

On the surface, the interpreter will actually execute these two sentences, but there is a big article in the code of @w1, @function name is a syntactic sugar of python.

The above example @w1 will perform the following operations internally:
Execute the w1 function
Execute the w1 function, and use the functions below @w1 as the parameters of the w1 function, that is: @w1 is equivalent to w1(f1) So, it will be executed internally:

def inner(): 
    #验证1
    #验证2
    #验证3
    f1()  # func是参数,此时func等于f1
return inner  # 返回的inner,inner代表的是函数,非执行函数,其实就是将原来的f1函数塞进另外一个函数中

The return value of w1
Assign the return value of the executed w1 function to the function name f1 of the function below @w1, namely:


 新f1 = def inner(): 
             #验证 1
             #验证 2
             #验证 3
             原来f1()
         return inner

Therefore, when the business department wants to execute the f1 function in the future, it will execute the new f1 function, first execute the verification inside the new f1 function, then execute the original f1 function, and then return the return value of the original f1 function to the business caller.

In this way, the verification function is executed, and the content of the original f1 function is executed, and the return value of the original f1 function is returned to the business caller. Low BBB Do you understand? If you don't understand, I will go to your house to help you solve it tonight! ! !

Advanced case

[Python] Python realizes the word guessing game-challenge your intelligence and luck!

[python] Python tkinter library implements GUI program for weight unit converter

[python] Use Selenium to get (2023 Blog Star) entries

[python] Use Selenium and Chrome WebDriver to obtain article information in [Tencent Cloud Studio Practical Training Camp]

Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition

[Fun with Python series [Xiaobai must see] Python multi-threaded crawler: download pictures of emoticon package websites

[Play with Python series] [Must-see for Xiaobai] Use Python to crawl historical data of Shuangseqiu and analyze it visually

[Play with python series] [Must-see for Xiaobai] Use Python crawler technology to obtain proxy IP and save it to a file

[Must-see for Xiaobai] Python image synthesis example using PIL library to realize the synthesis of multiple images by ranks and columns

[Xiaobai must see] Python crawler actual combat downloads pictures of goddesses in batches and saves them locally

[Xiaobai must see] Python word cloud generator detailed analysis and code implementation

[Xiaobai must see] Python crawls an example of NBA player data

[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python

[Must-see for Xiaobai] Technical realization of using Python to download League of Legends skin pictures in batches

[Xiaobai must see] Python crawler data processing and visualization

[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory

[Must-see for Xiaobai] Use Python to generate a personalized list Word document

[Must-see for Xiaobai] Python crawler combat: get pictures from Onmyoji website and save them automatically

Xiaobai must-see series of library management system - sample code for login and registration functions

100 Cases of Xiaobai's Actual Combat: A Complete and Simple Shuangseqiu Lottery Winning Judgment Program, Suitable for Xiaobai Getting Started

Geospatial data processing and visualization using geopandas and shapely (.shp)

Use selenium to crawl Maoyan movie list data

Detailed explanation of the principle and implementation of image enhancement algorithm Retinex

Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis

Introductory Guide to Crawlers (7): Using Selenium and BeautifulSoup to Crawl Douban Movie Top250 Example Explanation [Reptile Xiaobai must watch]

Getting Started Guide to Crawlers (6): Anti-crawlers and advanced skills: IP proxy, User-Agent disguise, Cookie bypass login verification and verification code identification tools

Introductory Guide to Crawlers (5): Distributed Crawlers and Concurrency Control [Implementation methods to improve crawling efficiency and request rationality control]

Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API

Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies

Getting started with crawlers (2): How to use regular expressions for data extraction and processing

Getting started with reptiles (1): Learn the basics and skills of reptiles

Application of Deep Learning Model in Image Recognition: CIFAR-10 Dataset Practice and Accuracy Analysis

Python object-oriented programming basics and sample code

MySQL database operation guide: learn how to use Python to add, delete, modify and query operations

Python file operation guide: encoding, reading, writing and exception handling

Use Python and Selenium to automate crawling#【Dragon Boat Festival Special Call for Papers】Explore the ultimate technology, and the future will be due to you"Zong" #Contributed articles

Python multi-thread and multi-process tutorial: comprehensive analysis, code cases and optimization skills

Selenium Automation Toolset - Complete Guide and Tutorials

Python web crawler basics advanced to actual combat tutorial

Python introductory tutorial: master the basic knowledge of for loop, while loop, string operation, file reading and writing and exception handling

Pandas data processing and analysis tutorial: from basics to actual combat

Detailed explanation of commonly used data types and related operations in Python

[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model

Introductory Python programming basics and advanced skills, web development, data analysis, and machine learning and artificial intelligence

Graph prediction results with 4 regression methods: Vector Regression, Random Forest Regression, Linear Regression, K-Nearest Neighbors Regression

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/132317870