Python learning Day12 Python decorator

Python decorators

Original source:  Wu Peiqi 

The decorator is a function that is often used in program development. If the decorator is used, the development efficiency will be even more powerful, so this is also a question that must be asked in the Python interview, but for many novices, this function is a bit confusing. Just bypass it, and then hang up when the interview is asked, because decorators are the basic knowledge of program development, and this is not possible. Don't tell others that you know Python, read the following articles, and make sure you learn decorators.

1. First understand this code

# ### First wave#### 
def foo():
     print  ' foo '
 
foo #represents      a function 
foo()    #represents the execution of the foo function
 
# ### Second wave#### 
def foo():
     print  ' foo '
 
foo = lambda x: x + 1
 
foo()    #Execute the following lambda expression instead of the original foo function, because the function foo has been redefined

2. The demand is coming

The start-up company has N business departments and 1 basic platform department. The basic platform is responsible for providing the underlying functions, such as: database operations, redis calls, monitoring API and other functions. When business departments use basic functions, they only need to call the functions provided by the basic platform. as follows:

# ############## The functions provided by the base 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, but the developers of the basic platform did not pay attention to the 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 to all the functions provided by the platform, that is, to verify the functions before executing the functions.

The boss gave the job to Low B, and he did this:

Negotiate with each business department, write code for each business department, and verify before calling the functions of the basic platform. Eh, this way the base platform doesn't need any modifications.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324811725&siteId=291194637