Full analysis of Python module knowledge
Module definition
A Python module (Module) is a file that ends in .py and contains data, functions, classes, etc. Usually it is a script that can be executed directly, or a bunch of code similar to library functions.
What are the benefits of using modules
- Organize your code logically for easy management and maintenance.
- Improve code readability
- Data, functions, and classes in the module are convenient for others to call
- Avoid variables/functions with the same name
Classification of modules
- Built-in modules: libraries that come with it are called built-in libraries of Python, such as sys, os
- **Third-party modules: ** So-called third-party libraries (open source libraries), you need to install them separately
- **Custom modules: **modules written by users (can be used as third-party modules for others)
Several ways to import modules
The principle of import is to search for the corresponding python file or package in the specified range, execute it, and get the method in it.
In Python, the keyword import is used to import a certain module. The commonly used import methods are as follows.
Search order of imported modules
- Search the current directory.
- Not in the current directory, Python searches every directory under the shell variable PYTHONPATH (the module search path is stored in the sys.path variable of the system module. The variable contains the current directory, PYTHONPATH and the default directory determined by the installation process).
- If none is found, Python will check the default path. Under UNIX, the default path is generally /usr/local/lib/python/.
**The general import rules are as follows: **
In the same package:
- import module name
- Function call: module name. function()
In different packages:
- import package 1. package 2. module name
- Function call: package 1. package 2. module name. function ()
**Several modules commonly used in Python are as follows: **