程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python3 tutorial: modular programming and decorators

編輯:Python

Python Modular programming for

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 .

Package down and package up

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 .

Python Nested functions and decorators for

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 .

About Python A summary of decorators

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved