python中的模块、库、包有什么区别?
模块:文件级别的组织
.py 结尾的那个文件。它就是一个 Python 文件,用来放代码的,功能就是组织代码,解决代码复用的问题。.py 文件,然后导入就行了。这就相当于“模块”了。math_utils.py 文件,里面写了个求平方的函数:# math_utils.py def square(x):
"""计算 x 的平方"""
return x * x
math_utils.py 文件就是一个模块,我们可以在其他地方引入它,像这样:# main.py import math_utils
print(math_utils.square(5)) # 输出 25
.py 文件就是一个模块,模块就是Python的基础组织单元。这个“模块”的概念可以说相当简单。小贴士:模块名就是 .py文件的名字,import 时千万别加.py,直接import math_utils就行,少那俩字符可不是偷懒,是规范哦。
库:成套的工具集合
requests 这个库,它是用来做 HTTP 请求的,模块多得很,不止一个 requests.py。你要用这个库,通常会先安装它,然后用其中的功能。比如我们请求一个网页:import requests response = requests.get('https://api.example.com/data')
print(response.json())
pandas 是做数据分析的库,里面有 Series 和 DataFrame 等模块,而 scikit-learn 是机器学习的库,包含各种分类、回归模块。包:带有结构的文件夹
__init__.py 文件的文件夹”。听着简单?它确实也不复杂,但有了它,库里的模块组织就有层级结构了。包允许我们将模块分层组织,适合于大型项目或库。很多Python大厂库,比如Django和Flask,都是通过包的方式组织代码。data_processing/
│
├── __init__.py # 标记为包
├── text_processing/
│ ├── __init__.py # 标记为包
│ └── text_utils.py
├── image_processing/
│ ├── __init__.py # 标记为包
│ └── image_utils.py
└── audio_processing/
├── __init__.py # 标记为包
└── audio_utils.py
from data_processing.text_processing import text_utils
from data_processing.image_processing import image_utils
小贴士:每个文件夹里都要有 __init__.py文件。没有这个文件,Python 就不知道该文件夹是包,会把它当成普通文件夹处理。
__init__.py 主要是告诉 Python:这是一整个“包”,这样就能让我们写的代码更整洁、组织得更有层次,尤其是在涉及到大量模块时,非常方便。包 VS 库:有包未必是库,库未必全是包
pandas,其实是一个库,包含了多个包结构。代码示例:简单实现一个包
text_tools/
├── __init__.py
├── converter.py
└── utils.py
converter.py提供转换功能。utils.py提供一个辅助函数。
# text_tools/converter.py from .utils import is_string
def to_upper(text):
"""转换为大写"""
if is_string(text):
return text.upper()
return Nonedef to_lower(text):
"""转换为小写"""
if is_string(text):
return text.lower()
return None
# text_tools/utils.py def is_string(value):
"""检查是否为字符串"""
return isinstance(value, str)
# text_tools/__init__.py from .converter import to_upper, to_lower
text_tools 包,并使用其中的 to_upper 和 to_lower 方法:# main.py from text_tools import to_upper, to_lower
print(to_upper("hello world")) # 输出:HELLO WORLD
print(to_lower("HELLO WORLD")) # 输出:hello world
__init__.py,我们可以指定哪些方法可以直接从包中导入,保持代码干净整洁。小结
模块:就是一个 .py文件,最小的代码组织单元。库:是一组功能相关的模块集合,常常包含多个模块。 包:带有 __init__.py文件的文件夹,允许模块按层次结构组织。