Let's first introduce the application scenario of modular programming with an example , There's one called requirements.py Of python3 file , Two of them are used to print a string in different order :
def example1():
a = 'hello world!'
print (a)
print (a[::-1])
def example2():
b = 'hello again!'
print (b)
print (b[::-1])
if __name__ == '__main__':
example1()
example2()
The results are as follows :
[[email protected]-manjaro decorator]$ python3 requirements.py
hello world!
!dlrow olleh
hello again!
!niaga olleh
The same printing function is used in both functions , At this time we can consider , Is it possible to encapsulate these two print statements as a function , So it can be reused ? This is the rudiment of modular programming thinking , Let's start with a modular transformation of the sample code :
def rprint(para):
print (para)
print (para[::-1])
def example1():
a = 'hello world!'
rprint(a)
def example2():
b = 'hello again!'
rprint (b)
if __name__ == '__main__':
example1()
example2()
Here we encapsulate the function of two print statements into rprint Function of , The results are as follows :
[[email protected]-manjaro decorator]$ python3 requirements.py
hello world!
!dlrow olleh
hello again!
!niaga olleh
The results are, of course, the same as before modularization .
In the previous chapter , We talked about python Modular programming in . Because there may be a lot of code to reuse in the programming process , At this time, we need to use a function to encapsulate , To avoid a lot of repetitive work . But if you look at it in detail , This encapsulation pattern only solves one kind of problems : Encapsulation down . Let's take another look at the code structure in the improved sample :
.
├── example1
│ └── rprint
└── example2
└── rprint
We can find out , It's reused here rprint It actually belongs to two example The lower layer of the function , We can call it a downward encapsulation rprint function . that , If we transform the modules that need to be reused , It becomes the following code structure , What kind of way do we need to achieve it ?
.
├── example
│ └── rprint1
└── example
└── rprint2
Problem interpretation : The meaning of this code structure is , There's a big one example function , The function is nested with different rprint Functions can perform different functions . For ease of understanding , The reader can imagine that there are two functions example1 and example2, Of these two functions, except rprint1 and rprint2 These two function modules are not consistent , The other parts are exactly the same , That is, shared .
First , In order to answer the questions in the above chapters , To construct such a python Test code :
def example1():
def rprint1(para):
print (para)
a = 'hello world!'
rprint1(a)
def example2():
def rprint2(para):
print (para[::-1])
a = 'hello world!'
rprint2(a)
if __name__ == '__main__':
example1()
example2()
The execution result of the above code is :
[[email protected]-manjaro decorator]$ python3 requirements.py
hello world!
!dlrow olleh
This case uses python Use of nested functions in , Other functions can be nested in a function . Here we notice , Although in order to run in the same code string , Two example The names of functions are different , But actually the content is exactly the same , Code structure in line with the legacy issues in the previous section . The question we need to consider here is , Can we package it up , take example The code implementation of the same function is classified ? So we need to introduce the use of decorators , Here we show directly how to construct a decorator , And the effect of the decorator .
''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :857662006 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
def example(func):
def wrapper(*args, **kwargs):
a = 'hello world!'
return func(a)
return wrapper
@example
def rprint1(para):
print (para)
@example
def rprint2(para):
print (para[::-1])
if __name__ == '__main__':
rprint1()
rprint2()
The execution result of this code is :
[[email protected]-manjaro decorator]$ python3 decorator.py
hello world!
!dlrow olleh
From the results we can see that , This code achieves the same effect . adopt example This decorator , It not only encapsulates the functions implemented in the upper functions , And there's another big significance , Pass parameters to the underlying function through the decorator . This makes , We finally call rprint Function , You don't need to pass in any parameters , Because in example Parameters that can be shared have been defined in .
Python The decorator is not a very difficult feature to implement , Its key significance lies in the realization of modular programming with upward encapsulation . In our past programming implementation , More commonly used for downward encapsulation 、 Reusable code modules . Through here Python The decorator features provided , We can also encapsulate the code modules shared outside the function . therefore , Features of downward encapsulation and upward encapsulation implemented by functions and decorators respectively , Together, it forms a modular programming mode to improve coding efficiency and readability .