今日目标:
- 理解模块和包的概念。
- 学习如何创建和导入模块。
- 掌握常用的内置模块。
- 学习使用第三方包。
- 了解Python包管理工具pip。
第一部分:什么是模块和包?
随着程序变得越来越复杂,我们需要将代码组织成多个文件:
- 模块(Module):一个.py文件就是一个模块
- 包(Package):包含多个模块的目录(需要有__init__.py文件)
优点:
- 代码重用
- 命名空间管理
- 易于维护
第二部分:创建和使用模块
- 创建第一个模块:
# 创建文件 calculator.py
# 这是一个简单的计算器模块
def add(a, b):
"""返回两个数的和"""
return a + b
def subtract(a, b):
"""返回两个数的差"""
return a - b
def multiply(a, b):
"""返回两个数的积"""
return a * b
def divide(a, b):
"""返回两个数的商"""
if b == 0:
raise ValueError("除数不能为零")
return a / b
# 模块级别的变量
PI = 3.14159
VERSION = "1.0"
# 测试代码
if __name__ == "__main__":
# 这个代码只有在直接运行该模块时才会执行
print("测试计算器模块:")
print(f"5 + 3 = {add(5, 3)}")
print(f"PI = {PI}")
2 导入模块:
# 创建新文件 day15_module.py
# 方法1:导入整个模块
import calculator
result = calculator.add(10, 5)
print(f"10 + 5 = {result}")
print(f"PI = {calculator.PI}")
# 方法2:导入特定函数
from calculator import add, multiply
result = add(10, 5)
print(f"使用import导入的add: {result}")
# 方法3:导入所有内容(不推荐,容易造成命名冲突)
from calculator import *
result = subtract(10, 5)
print(f"10 - 5 = {result}")
# 方法4:给模块或函数起别名
import calculator as calc
from calculator import divide as div
result = calc.multiply(10, 5)
print(f"使用别名调用: 10 * 5 = {result}")
第三部分:创建和使用包
3 创建包结构:
my_package/
├── __init__.py
├── math_utils.py
├── string_utils.py
└── data/
├── __init__.py
└── processor.py
4 包中的模块:
# my_package/math_utils.py
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# my_package/string_utils.py
def reverse_string(s):
return s[::-1]
def count_vowels(s):
vowels = "aeiouAEIOU"
count = 0
for char in s:
if char in vowels:
count += 1
return count
5 使用包:
# 导入包中的模块
from my_package import math_utils, string_utils
print(math_utils.factorial(5)) # 120
print(string_utils.reverse_string("hello")) # olleh
# 导入包中子模块
from my_package.data import processor
# 相对导入(在包内部使用)
# from ..math_utils import factorial
第四部分:常用的内置模块
6 math模块:
import math
# 数学常数
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
# 数学函数
print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
print(math.log(100, 10)) # 2.0
print(math.sin(math.pi/2)) # 1.0
# 实用函数
print(math.floor(3.7)) # 3
print(math.ceil(3.2)) # 4
print(round(3.14159, 2)) # 3.14
7 random模块:
import random
# 生成随机数
print(random.random()) # [0, 1)之间的随机小数
print(random.uniform(1, 10)) # [1, 10)之间的随机小数
print(random.randint(1, 6)) # [1, 6]之间的随机整数
# 随机选择
colors = ["红", "绿", "蓝", "黄"]
print(random.choice(colors)) # 随机选择一个元素
print(random.sample(colors, 2)) # 随机选择多个不重复的元素
random.shuffle(colors) # 打乱顺序
print(colors)
8 datetime模块:
from datetime import datetime, date, time, timedelta
# 当前日期时间
now = datetime.now()
print(f"当前时间: {now}")
print(f"年份: {now.year}, 月份: {now.month}, 日期: {now.day}")
# 创建特定日期
birthday = date(2000, 1, 1)
print(f"生日: {birthday}")
# 格式化日期
formatted = now.strftime("%Y年%m月%d日 %H:%M:%S")
print(f"格式化: {formatted}")
# 解析字符串为日期
date_str = "2023-12-25 20:30:00"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(f"解析的日期: {parsed_date}")
# 日期运算
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
print(f"明天: {tomorrow}")
print(f"上周: {last_week}")
9 os模块:
import os
# 文件和目录操作
print(os.getcwd()) # 当前工作目录
# 列出目录内容
print(os.listdir('.'))
# 创建和删除目录
if not os.path.exists('test_dir'):
os.mkdir('test_dir')
# 检查路径
print(os.path.isfile('test.txt'))
print(os.path.isdir('test_dir'))
# 路径拼接
file_path = os.path.join('test_dir', 'test.txt')
print(file_path)
10 json模块:
import json
# Python对象转换为JSON字符串
data = {
"name": "小明",
"age": 18,
"scores": [85, 92, 78],
"is_student": True
}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# 将JSON字符串保存到文件
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# 从JSON字符串解析Python对象
data_loaded = json.loads(json_str)
print(data_loaded['name'])
# 从文件加载JSON
with open('data.json', 'r', encoding='utf-8') as f:
data_from_file = json.load(f)
第五部分:使用第三方包
11 使用pip安装包:
# 在命令行中执行
pip install requests numpy pandas
# 查看已安装的包
pip list
# 安装特定版本
pip install requests==2.28.1
# 升级包
pip install --upgrade requests
# 卸载包
pip uninstall requests
12 使用requirements.txt:
# requirements.txt文件内容
requests==2.28.1
numpy>=1.21.0
pandas
安装所有依赖:
pip install -r requirements.txt
今日小结与练习
今日核心概念:
- 模块:一个.py文件,包含可重用的代码
- 包:包含__init__.py文件的目录,包含多个模块
- 导入方式:import, from … import, 别名
- 内置模块:math, random, datetime, os, json等
- 第三方包:使用pip安装和管理
- if __name__ == “__main__”:模块测试代码
动手练习(务必完成):
练习1:创建个人工具包
创建一个名为my_tools的包,包含以下模块:
- math_tools.py:包含你常用的数学函数
- string_tools.py:包含字符串处理函数
- file_tools.py:包含文件操作函数
然后在主程序中导入并使用这些工具。
练习2:学生信息管理系统(模块化版)
将之前的学生信息管理系统拆分成多个模块:
- models.py:包含Student, Teacher, Course等类
- storage.py:包含文件读写功能
- ui.py:包含用户界面逻辑
- main.py:主程序,导入其他模块并运行
练习3(挑战):天气查询程序
使用requests库(需要先安装)创建一个简单的天气查询程序:
- 安装requests库:pip install requests
- 使用免费的天气API(如https://api.openweathermap.org)
- 让用户输入城市名,查询并显示天气信息
- 将查询结果保存到JSON文件中
今天的知识对于组织大型项目超级重大。模块化编程是现代软件开发的基础,必定要掌握好!
第十五天完成,你已经学会了如何组织大型Python项目!
© 版权声明
文章版权归作者所有,未经允许请勿转载。
收藏起来慢慢学