Skip to content

模块

  • Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和 Python 语句。

导入模块

  • import 语句用于导入模块,语法如下:
python
import 模块名
  • from import 语句用于从模块中导入指定的函数或变量,语法如下:
python
from 目录或者文件 import 函数、变量

多层级导入模块

同级目录导入模块

  • 结构如下

|--base_dir

    |--module1.py

        def func1()

        def func2()

    |--module2.py

  • 要想在 module2.py 中导入 module1.py 中的 func1,func2 函数,直接使用以下命令即可。
python
import module1
# 或者
from module1 import func1,func2

从当前目录的子目录中导入模块

  • 结构如下

|--base_dir

    |--son_dir

        |--module1.py

            def func1()

            def func2()

    |--module2.py

  • 此时,要想在 module2.py 中导入 module1.py 中的 func1,func2 函数,需要在 module1.py 所在的文件夹 son_dir 下添加一个__init__.py文件,只有这样,son_dir 才会成为一个 package,否则不能调用。

|--base_dir

    |--son_dir

        |--__init__.py # 空文件即可

        |--module1.py

            def func1()

            def func2()

    |--module2.py

python
import module1
# 或者
from module1 import func1,func2

从父目录中导入模块

  • 结构如下

|--base_dir

    |--module1.py

        def func1()

        def func2()

    |--son_dir

        |--module2.py

我们想在 son_dir.module2.py 中导入 base_dir.module1.py 中的 func1,func2 函数。需要再 module2.py 中添加以下代码。

python
import sys
sys.path.append('../base_dir')
from module1 import func1,func2

从任意路径下导入模块

  • 结构如下

|--any_dir1

    |--module1.py

        def func1()

        def func2()

|--any_dir2

    |--module2.py

需要在 module2.py 中添加以下代码。

python
import sys
sys.path.append('../any_dir1') # 就是提前先把any_dir1添加到路径中
from module1 import func1,func2

内置模块

系统自动的模块,不需要额外安装,直接 import 即可

  • random # 随机数模块
  • math # 数学模块
  • time # 时间模块
  • datetime # 日期时间模块
  • os # 操作系统模块
  • sys # 系统模块
  • re # 正则表达式模块
  • json # JSON 模块
  • csv # CSV 模块
  • xml # XML 模块
  • sqlite3 # SQLite 数据库模块
  • pymysql # MySQL 数据库模块
  • requests # HTTP 请求模块
  • bs4 # Beautiful Soup 模块
  • lxml # lxml 模块
  • numpy # NumPy 模块
  • pandas # Pandas 模块
  • matplotlib # Matplotlib 模块
  • seaborn # Seaborn 模块

第三方模块

第三方开发的模块,需要额外安装pip install 模块名

  • redis # Redis 数据库模块
  • pymongo # MongoDB 数据库模块
  • scipy # SciPy 模块
  • sklearn # Scikit-learn 模块
  • tensorflow # TensorFlow 模块
  • pytorch # PyTorch 模块
  • django # Django 框架模块
  • flask # Flask 框架模块
  • fastapi # FastAPI 框架模块

自定义模块

自己开发的模块,需要自己编写代码,并将其保存为.py 文件,然后使用 import 语句导入