首页 / Python3 入门教程 / 包与第三方模块

Python3 入门教程

包与第三方模块

本教程共 70 篇 · 第 29 篇 · 更新于 2026-07-22 · 约 3 分钟阅读

PythonPython3 入门教程Python 包piprequirements.txt镜像源

29. 包与第三方模块

本节目标:理解包的结构,掌握 pip 的使用,能安装和管理第三方库。

什么是包

包(package)是包含多个模块的文件夹。当项目变大,单个文件装不下时,就需要用包来组织代码。

一个最简单的包结构:

mypackage/
    __init__.py
    math_tools.py
    string_tools.py

__init__.py 是包的标志文件,告诉 Python「这个文件夹是一个包」。它可以为空,也可以写初始化代码。

Note

Python 3.3+ 引入了「隐式命名空间包」,没有 __init__.py 也能被识别为包。但为了兼容性和清晰性,建议每个包目录都保留 __init__.py

导入包里的模块

import mypackage.math_tools
from mypackage import string_tools
from mypackage.math_tools import add

init.py 的作用

__init__.py 在包被导入时执行。常用它来控制包的公开接口:

# mypackage/__init__.py
from .math_tools import add, multiply
from .string_tools import slugify

__all__ = ["add", "multiply", "slugify"]

这样用户可以直接:

from mypackage import add, slugify
Tip

__all__ 定义了 from mypackage import * 时导入的名字。没有它,* 不会导入任何子模块的内容。

嵌套包

包可以嵌套,形成层级结构:

mypackage/
    __init__.py
    core/
        __init__.py
        models.py
    utils/
        __init__.py
        helpers.py
from mypackage.core.models import User
from mypackage.utils.helpers import format_date

pip:Python 的包管理器

pip 是安装第三方库的工具,相当于 Python 的「应用商店」。

安装包

pip install requests          # 安装 requests
pip install requests==2.28.1  # 安装指定版本
pip install "requests>=2.28"  # 安装大于等于某版本

查看已安装包

pip list
pip show requests             # 查看某个包的详细信息

卸载包

pip uninstall requests

升级包

pip install --upgrade requests
Warning

不要直接 pip install 到系统 Python 里,容易搞坏环境。下一节会讲虚拟环境,那是正确的做法。

换国内镜像源

默认源在国外,下载慢。可以换成国内的:

# 临时使用
pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple

# 永久配置
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

常用国内镜像:

镜像地址
清华https://pypi.tuna.tsinghua.edu.cn/simple
阿里云https://mirrors.aliyun.com/pypi/simple/
中科大https://pypi.mirrors.ustc.edu.cn/simple/

requirements.txt

团队项目里,用 requirements.txt 记录所有依赖:

pip freeze > requirements.txt

生成的文件长这样:

requests==2.28.1
numpy==1.24.0
pandas==1.5.0

新成员部署环境时,一行命令安装所有依赖:

pip install -r requirements.txt
Tip

生产环境的 requirements.txt 建议锁定精确版本,避免「在我电脑上能跑」的问题。


来源:参考了 runoob「Python3 模块」、w3cschool「Python3 模块」等,改写后所得。