author : Han Xinzi @ShowMeAI
Tutorial address :http://www.showmeai.tech/tuto...
This paper addresses :http://www.showmeai.tech/article-detail/84
Statement : copyright , For reprint, please contact the platform and the author and indicate the source
In the process of program development , The file code is getting longer and longer , Maintenance is becoming more and more difficult . We write many different functions into functions , Put it in different files , Easy to manage and call . stay Python in , One .py File is called a module (Module).
Using modules can greatly improve the maintainability of the code , And when a module is written , Can be quoted elsewhere . We are using python When completing a lot of complex work , Other third parties are often cited 3 Square module , Benefit from strong python Community , We accomplish almost any task , There can be corresponding convenient, quick and referenced libraries and modules to assist .
A module is a file that contains all the functions and variables you define , With .py The suffix ends . Modules can be introduced and used by other programs .
Here is a use python Examples of modules in the standard library .
import sys
print(' The command line parameters are as follows :')
for i in sys.argv:
print(i)
print('\n\nPython Path is :', sys.path, '\n')
The results are shown below :
$ python using_sys.py Parameters 1 Parameters 2
The command line parameters are as follows :
using_sys.py
Parameters 1
Parameters 2
Python Path is : ['/root', '/usr/lib/python3.10', '/usr/lib/python3.10/plat-x86_64-linux-gnu', '/usr/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages']
Explain the following :
Want to use Python modular , Just execute it in another source file import sentence , The grammar is as follows :
import module1[, module2[,... moduleN]
When the interpreter encounters import sentence , If the module can be found in the current search path , Will be imported directly .
The search path is a list of all directories that the interpreter will search first . If you want to import modules showmeai, You need to put the command at the top of the script :
showmeai.py File code
def print_welcome( par ):
print ("Welcome : ", par)
return
test.py File code
# The import module
import showmeai
# Now you can call the functions contained in the module
showmeai.print_welcome("ShowMeAI")
The output of the above code :
$ python3 test.py
Welcome : ShowMeAI
When we use import At the time of statement ,Python The interpreter will look for the corresponding module in the search path , The search path is made up of a series of directory names , It's in Python When compiling or installing , Installing new libraries should also change . The search path is stored in sys Module path Variable , Do a simple experiment , In the interactive interpreter , Enter the following code :
>>> import sys
>>> sys.path
['', '/usr/lib/python3.10', '/usr/lib/python3.10/plat-x86_64-linux-gnu', '/usr/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages']
>>>
sys.path The output is a list of paths , The first one is an empty string '', perform python The current directory of the interpreter .
Let's create a code as follows fibo.py file , Put it on sys.path In any directory in :
def fib(n): # Define the n The Fibonacci sequence of
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib_new(n): # Back to n The Fibonacci sequence of
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
Then enter Python Interpreter , Use the following command to import this module :
>>> import fibo
You can use the module name to access the function :
>>>fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib_new(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
For frequently used functions , You can assign it to a local name :
>>> my_fib = fibo.fib
>>> my_fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
Python Of from Statement allows you to import a specified part from a module into the current namespace , The grammar is as follows :
from modname import name1[, name2[, ... nameN]]
for example , To import a module fibo Of fib function , Use the following statement :
>>> from fibo import fib, fib_new
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
This statement will not take the whole fibo Modules are imported into the current namespace , It will only fibo Inside fib Function is introduced .
It is also possible to import all the contents of a module into the current namespace , Just use the following statement :
from modname import *
for example , To import a module fibo Of all function , Use the following statement :
>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
Python It comes with some standard module Libraries , Some modules are built directly into the parser , Can use very efficiently .
For example module sys, It's built into every Python The parser . Variable sys.ps1 and sys.ps2 Defines the string corresponding to the main prompt and secondary prompt :
>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('ShowMeAI!')
ShowMeAI!
C>
Package is a kind of management Python The form of the module namespace , We often use 「 package . modular 」 To import modules in the form of , For example, the name of a module is C.D, So he means a bag C Sub modules in D. Using this form, you don't have to worry about module duplicate names between different libraries .
Suppose you want to design a set of modules for unified processing of video files and data ( Or call it a " package ").
There are many different audio file formats available ( It's basically distinguished by suffixes , for example : .mp4,.wmv,.avi,.mkv), So you need to have a growing set of modules , Used to convert between different formats .
And for this data , There are many different operations , So you also need a huge set of modules to handle these operations .
Here is a possible package structure ( In a hierarchical file system ):
video/ Top package
__init__.py initialization video package
formats/ File format conversion package
__init__.py
mp4read.py
mp4write.py
aviread.py
aviwrite.py
mkvread.py
mkvwrite.py
wmvread.py
wmvwrite.py
...
audio/ Package effect
__init__.py
io.py
fx.py
tools.py
...
editor/ filters subpackage
__init__.py
period.py
faster.py
slower.py
...
When importing a package ,Python Will be based on sys.path To find the subdirectories contained in this package .
The directory contains only one called \_\_init\_\_.py Is a package . The simplest treatment is to put an empty \_\_init\_\_.py file .
Users can import only one specific module in a package at a time , such as :
import video.audio.io
This will import sub modules :video.audio.io. He must use his full name to access :
video.audio.io.readfile(input)
Another way to import sub modules is :
from video.audio import io
This will also import sub modules : io, And he doesn't need those long prefixes , So he can use :
io.readfile(input)
Another change is to import a function or variable directly :
from video.audio.io import readfile
alike , This method will import sub modules : io, And you can use his readfile() function :
readfile(input)
When using from package import item In this form , Corresponding item It can be a sub module in the package ( subpackage ), Or any other name in the package , Like functions , Class or variable .
import Grammar will first put item As a package definition name , If not , Then try to import according to a module . If you haven't found it yet , Throw a exc:ImportError abnormal .
If we use shapes like import item.subitem.subsubitem This form of import , Except for the last term , All have to be bags , The last item can be a module or a package , No, but class , The name of a function or variable .
Please click to B I'm looking at it from the website 【 Bilingual subtitles 】 edition
https://www.bilibili.com/vide...
The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , Babies who can surf the Internet scientifically can also use google colab One click operation and interactive operation learning Oh !
This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :