Skip to content

Python 模块

一句话解释

模块 是 .py file 包含 Python code 那个 能 是 imported and reused in other files.

用大白话说

Python 模块是 简单地 .py file. 任何 Python file 能是 imported 通过它的 name (不使用 .py extension) using import statement. This lets you split code into focused, reusable files instead of one giant script.

For example, if you have a file math_utils.py with a function def 添加(, b), another file can do 从 math_utils 导入添加 and use it. The module's name becomes a namespace, preventing name collisions between files.

Python's standard library is a collection of modules — os, sys, math, JSON, datetime, and many more. You import them the same way. Modules can also be organized into packages (folders of modules) for larger projects.

示例

python
# math_utils.py
def add(a, b):
    return a + b

PI = 3.14159

# main.py
from math_utils import add, PI

print(add(2, 3))  # 5
print(PI)         # 3.14159

math_utils.py 是 模块. 主要.py 导入 and uses 它的 函数 and 变量.

常见混淆

  • 容易混淆的对象: 包

    关键区别: 模块 是 单个 .py file. 包 是 folder 的 模块 使用 __init__.py file. 每个 包 包含 模块, 但 单个 模块 是 不 包. 包 组织 related 模块 到 hierarchy.

相关术语

相关资源

相关课程

  • 函数

    模块 分组 related 函数

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表