Author: Han Xinzi@ShowMeAI
Tutorial address: http://www.showmeai.tech/tuto...
Article address: http://www.showmeai.tech/article-detail/84
Notice: All Rights Reserved. Please contact the platform and the author for reprint and indicate the source
In the process of program development, the file code is getting longer and longer, and the maintenance is becoming more and more difficult. We write many different functions into functions and put them in different files to facilitate management and call. In Python, a py file is called a Module.
Using modules can greatly improve the maintainability of code, and when a module is written, it can be referenced elsewhere. When we use python to complete many complex tasks, we often refer to other third-party modules, benefiting from the strong python community. We can have corresponding convenient and quick referenced libraries and modules to assist us in almost any task.
A module is a file that contains all the functions and variables you define py suffix ends. Modules can be introduced and used by other programs.
The following is an example of using modules in the python standard library.
import sys print('The command line parameters are as follows:') for i in sys.argv: print(i) print('\n\nPython The path is:', sys.path, '\n')
The execution results are as follows:
$ python using_sys.py Parameter 1 Parameter 2 The command line parameters are as follows: using_sys.py Parameter 1 Parameter 2 Python The 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']
The explanation is as follows:
- import sys introduces sys. In the python standard library Py module; This is the first mock exam.
- sys.argv is a list of command line arguments.
- sys.path contains a list of paths where the Python interpreter automatically finds the required modules.
To use the Python module, just execute the import statement in another source file. The syntax is as follows:
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, if the module can be searched in the current search path, it will be imported directly.
The search path is a list of all directories that the interpreter will search first. If you want to import the module 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
# Import module import showmeai # Now you can call the functions contained in the module showmeai.print_welcome("ShowMeAI")
Output result of the above code:
$ python3 test.py Welcome : ShowMeAI
When we use the import statement, the Python interpreter will look for the corresponding module in the search path. The search path is composed of a series of directory names. It is determined when Python is compiled or installed. The installation of a new library should also be modified. The search path is stored in the path variable in the sys module. 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. The path output is a list of paths, the first of which is the empty string '', and the current directory where the python interpreter is executed.
We create a Fibo with the following code Py file, put it in sys In any directory in path:
def fib(n): # Fibonacci sequence defined to n a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print() def fib_new(n): # Return to the Fibonacci sequence of n result =  a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result
Then enter the Python interpreter and import this module with the following command:
>>> 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 them 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
4.from... import statement
Python's from statement allows you to import a specified part from the module into the current namespace. The syntax is as follows:
from modname import name1[, name2[, ... nameN]]
For example, to import the fib function of module fibo, 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 declaration will not import the whole fibo module into the current namespace. It will only introduce the fib function in fibo.
5.from... import * statement
It is also feasible to import all the contents of a module into the current namespace. Just use the following Declaration:
from modname import *
For example, to import all functions of module fibo, use the following statement:
>>> from fibo import * >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
6. Standard module
Python itself has some standard module libraries. Some modules are directly built in the parser and can be used efficiently.
For example, the module sys is built into every Python 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 form of managing Python module namespace. We often import modules in the form of "package. Module". For example, if the name of a module is C.D, it represents the sub module D in package C. 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 (or called a "package") to uniformly process video files and data.
There are many different audio file formats (basically distinguished by suffixes, such as. mp4,. wmv,. avi,. mkv), so you need to have a group of increasing modules to convert between different formats.
And there are many different operations for these video data, so you also need a large set of modules to deal with 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 sub package __init__.py mp4read.py mp4write.py aviread.py aviwrite.py mkvread.py mkvwrite.py wmvread.py wmvwrite.py ... audio/ Sound effect sub package __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 import it according to sys Path to find the subdirectories contained in the package.
There is only one directory called\_\_ init\_\_.py file will be regarded as a package. The simplest treatment is to put an empty one\_\_ init\_\_.py file.
Users can import only specific modules in one package at a time, such as:
This will import the sub module: video audio. io. He must use his full name to access:
Another way to import sub modules is:
from video.audio import io
This will also import the sub module: io, and it does not need those verbose prefixes, so it can be used as follows:
Another change is to directly import a function or variable:
from video.audio.io import readfile
Similarly, this method will import the sub module: io, and you can directly use its readfile() function:
When using the form of from package import item, the corresponding item can be a sub module (sub package) in the package or other names defined in the package, such as functions, classes or variables.
The import syntax will first treat item as the name of a package definition. If it is not found, then try to import it according to a module. If not found, throw an exc:ImportError exception.
If we use the shape such as import item subitem. The import form of subitem, except the last item, must be a package, and the last item can be a module or package, but can not be the name of a class, function or variable.
8. Video tutorial
Please click to station B to view the version of [bilingual subtitles]
Data and code download
The code for this tutorial series can be found in github corresponding to ShowMeAI Download in, you can run in the local python environment. Babies who can surf the Internet scientifically can also directly use Google lab to run and learn through interactive operation!
The Python quick look-up table involved in this tutorial series can be downloaded and obtained at the following address:
ShowMeAI related articles recommended
- Introduction to python
- python installation and environment configuration
- python basic syntax
- python basic data type
- python operator
- python conditional control and if statement
- python loop statement
- python while loop
- python for loop
- python break statement
- python continue statement
- python pass statement
- python string and operation
- python list
- python tuple
- python dictionary
- python collection
- python function
- python iterators and generators
- python data structure
- python module
- python file reading and writing
- python file and directory operation
- python error and exception handling
- python object oriented programming
- python namespace and scope
- python time and date
ShowMeAI series tutorial recommendations
- Illustrated Python Programming: a series of tutorials from getting started to mastering
- Graphic data analysis: a series of tutorials from introduction to mastery
- Fundamentals of graphic AI Mathematics: a series of tutorials from introduction to mastery
- Illustrated big data technology: a series of tutorials from introduction to mastery