模块与包管理
组织代码,使用第三方库
模块概述
什么是模块
模块 是一个Python文件,包含变量、函数、类等。
# mymodule.py - 这就是一个模块
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
class Calculator:
pass
为什么使用模块
- 代码复用:写一次,多处使用
- 命名空间:避免命名冲突
- 代码组织:按功能分类
- 协作开发:不同人负责不同模块
导入模块
import语句
# 导入整个模块
import math
print(math.pi) # 3.14159...
print(math.sqrt(16)) # 4.0
# 导入多个模块
import os, sys, json
from...import语句
# 导入特定内容
from math import pi, sqrt
print(pi) # 3.14159...
print(sqrt(16)) # 4.0
# 导入所有(不推荐)
from math import *
别名
# 模块别名
import numpy as np
import pandas as pd
# 函数别名
from math import sqrt as square_root
print(square_root(16)) # 4.0
标准库
常用标准库
| 模块 | 用途 |
|---|---|
| os | 操作系统接口 |
| sys | Python运行时 |
| math | 数学函数 |
| random | 随机数 |
| datetime | 日期时间 |
| json | JSON处理 |
| re | 正则表达式 |
| collections | 高级数据结构 |
| itertools | 迭代工具 |
| functools | 函数工具 |
示例
# random
import random
print(random.randint(1, 100)) # 随机整数
print(random.choice([1, 2, 3])) # 随机选择
random.shuffle([1, 2, 3, 4, 5]) # 打乱列表
# datetime
from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
tomorrow = now + timedelta(days=1)
# collections
from collections import Counter, defaultdict
counter = Counter("hello") # {'l': 2, 'h': 1, 'e': 1, 'o': 1}
创建自己的模块
简单模块
# utils.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
PI = 3.14159
# main.py
import utils
print(utils.add(3, 5)) # 8
print(utils.PI) # 3.14159
__name__ 变量
# mymodule.py
def main():
print("模块被直接运行")
if __name__ == "__main__":
# 只有直接运行此文件时才执行
main()
包(Package)
什么是包
包 是包含多个模块的目录,必须有 __init__.py 文件。
mypackage/
├── __init__.py
├── module1.py
├── module2.py
└── subpackage/
├── __init__.py
└── module3.py
使用包
# 导入包中的模块
import mypackage.module1
from mypackage import module2
from mypackage.subpackage import module3
# 使用
mypackage.module1.some_function()
module2.another_function()
__init__.py
# mypackage/__init__.py
from .module1 import func1
from .module2 import func2
__all__ = ['func1', 'func2'] # 控制 from mypackage import *
pip包管理
pip基本命令
# 安装包
pip install 包名
pip install requests
# 指定版本
pip install requests==2.28.0
pip install "requests>=2.20,<3.0"
# 升级包
pip install --upgrade requests
# 卸载包
pip uninstall requests
# 查看已安装
pip list
pip show requests
# 导出依赖
pip freeze > requirements.txt
# 安装依赖
pip install -r requirements.txt
常用第三方库
| 库 | 用途 |
|---|---|
| requests | HTTP请求 |
| beautifulsoup4 | HTML解析 |
| pandas | 数据分析 |
| numpy | 数值计算 |
| matplotlib | 数据可视化 |
| flask | Web框架 |
| django | Web框架 |
| pytest | 测试框架 |
| pillow | 图像处理 |
使用示例
# requests
import requests
response = requests.get("https://api.github.com")
print(response.json())
# beautifulsoup4
from bs4 import BeautifulSoup
html = "<html><body><h1>Hello</h1></body></html>"
soup = BeautifulSoup(html, "html.parser")
print(soup.h1.text)
虚拟环境
为什么需要虚拟环境
- 隔离项目依赖
- 避免版本冲突
- 方便部署
创建和使用
# 创建虚拟环境
python -m venv myenv
# 激活(Windows)
myenv\Scripts\activate
# 激活(Mac/Linux)
source myenv/bin/activate
# 确认激活
which python # 应显示虚拟环境路径
# 安装依赖
pip install requests
# 退出虚拟环境
deactivate
项目结构建议
myproject/
├── venv/ # 虚拟环境(不提交到git)
├── src/ # 源代码
│ ├── __init__.py
│ └── main.py
├── tests/ # 测试
├── requirements.txt # 依赖列表
├── README.md
└── .gitignore
.gitignore
# 虚拟环境
venv/
env/
.venv/
# Python缓存
__pycache__/
*.pyc
实战示例
示例:项目结构
calculator/
├── calculator/
│ ├── __init__.py
│ ├── basic.py
│ └── advanced.py
├── tests/
│ └── test_calculator.py
├── main.py
└── requirements.txt
# calculator/basic.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
# calculator/advanced.py
import math
def power(base, exp):
return base ** exp
def sqrt(n):
return math.sqrt(n)
# calculator/__init__.py
from .basic import add, subtract
from .advanced import power, sqrt
__version__ = "1.0.0"
# main.py
from calculator import add, power
print(add(3, 5)) # 8
print(power(2, 10)) # 1024
练习
练习1:创建工具模块
# 创建一个string_utils.py模块,包含:
# - reverse_string(s): 反转字符串
# - count_words(s): 统计单词数
# - is_palindrome(s): 判断回文
# string_utils.py
def reverse_string(s):
return s[::-1]
def count_words(s):
return len(s.split())
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
本章小结
- 模块:Python文件,包含可复用的代码
- 导入:import、from...import
- 包:包含__init__.py的目录
- pip:安装和管理第三方库
- 虚拟环境:隔离项目依赖
下一步
恭喜完成编程语言入门篇!接下来进入实战项目篇。
→ 继续阅读:25-HelloWorld与基础练习