包
一句话解释
包 是 folder 的 Python 模块 使用 __init__.py file, letting 你 导入 它们 as 分组.
用大白话说
Python 包是 folder 那个包含多个模块 files plus 特殊 __init__.py file. __init__.py tells Python "这个 folder 是包," and it can hold initialization code or be empty. Packages let you organize related modules into a hierarchy.
For example, a myproject package might contain myproject/数据库.py, myproject/models.py, and myproject/__init__.py. You import submodules with 从 myproject.数据库 导入 连接. The dot notation reflects the folder structure.
Packages are how the Python ecosystem distributes code. When you pip 安装 numpy, you install a package. Packages can contain sub-packages, creating a tree of modules. Modern Python (3.3+) also supports namespace packages without __init__.py, but the classic structure remains common.
示例
# myproject/__init__.py (can be empty)
# myproject/database.py
def connect():
return "Connected"
# myproject/models.py
class User:
pass
# main.py
from myproject.database import connect
from myproject.models import User
print(connect()) # "Connected"myproject 是 包 (folder 使用 __init__.py). 你 导入 它的 模块 使用 点 notation.
常见混淆
容易混淆的对象: 模块
关键区别: 模块 是 单个 .py file; 包 是 folder 的 模块 使用 __init__.py. 包 分组 related 模块; 模块 是 one file 的 code 在内 or 之外 包.
相关术语
相关资源
相关课程
- 函数
包 组织 模块 的 函数
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。