第41集:模块导入与使用
学习目标
- 理解模块的概念和作用
- 掌握模块导入的多种方式
- 学会使用import语句
- 掌握from...import语句
- 理解模块的搜索路径
一、什么是模块?
模块是一个包含Python代码的文件,以.py为扩展名。
模块的作用
| 作用 | 说明 |
|---|---|
| 代码组织 | 将相关功能组织在一起 |
| 代码复用 | 在多个程序中使用同一模块 |
| 命名空间 | 避免命名冲突 |
| 提高可维护性 | 便于管理和修改 |
生活类比
- 模块就像"工具箱"
- 每个工具箱里有不同的工具(函数、类、变量)
- 需要什么工具就从工具箱里拿出来用
示例:模块的基本结构
# mymodule.py
"""这是一个示例模块"""
# 变量
PI = 3.14159
name = "我的模块"
# 函数
def greet(name):
"""问候函数"""
return f"你好,{name}!"
def add(a, b):
"""加法函数"""
return a + b
# 类
class Calculator:
"""计算器类"""
def __init__(self):
self.value = 0
def add(self, num):
self.value += num
return self.value二、导入模块的方式
方式1:导入整个模块
import math
# 使用模块中的功能
print(math.pi) # 输出:3.141592653589793
print(math.sqrt(16)) # 输出:4.0
print(math.pow(2, 3)) # 输出:8.0方式2:导入模块并起别名
import math as m
# 使用别名访问
print(m.pi) # 输出:3.141592653589793
print(m.sqrt(16)) # 输出:4.0
print(m.pow(2, 3)) # 输出:8.0方式3:导入模块中的特定内容
from math import pi, sqrt, pow
# 直接使用,不需要模块名前缀
print(pi) # 输出:3.141592653589793
print(sqrt(16)) # 输出:4.0
print(pow(2, 3)) # 输出:8.0方式4:导入模块中所有内容
from math import *
# 直接使用所有功能
print(pi)
print(sqrt(16))
print(sin(0))方式5:导入并重命名
from math import sqrt as square_root
# 使用新的名称
print(square_root(16)) # 输出:4.0三、标准库模块示例
示例1:math模块(数学函数)
import math
# 数学常量
print(f"π = {math.pi}")
print(f"e = {math.e}")
# 数学函数
print(f"abs(-5) = {math.fabs(-5)}") # 绝对值
print(f"ceil(3.2) = {math.ceil(3.2)}") # 向上取整
print(f"floor(3.8) = {math.floor(3.8)}") # 向下取整
print(f"sqrt(16) = {math.sqrt(16)}") # 平方根
print(f"pow(2, 3) = {math.pow(2, 3)}") # 幂运算
# 三角函数
print(f"sin(π/2) = {math.sin(math.pi/2)}")
print(f"cos(π) = {math.cos(math.pi)}")
print(f"tan(π/4) = {math.tan(math.pi/4)}")示例2:random模块(随机数)
import random
# 随机浮点数
print(f"random() = {random.random()}") # 0.0到1.0
print(f"uniform(1, 10) = {random.uniform(1, 10)}") # 1.0到10.0
# 随机整数
print(f"randint(1, 10) = {random.randint(1, 10)}") # 1到10
print(f"randrange(0, 10, 2) = {random.randrange(0, 10, 2)}") # 0到10,步长2
# 随机选择
colors = ["红", "绿", "蓝", "黄"]
print(f"choice = {random.choice(colors)}")
print(f"choices = {random.choices(colors, k=2)}")
print(f"sample = {random.sample(colors, 2)}")
# 洗牌
cards = ["A", "2", "3", "4", "5"]
random.shuffle(cards)
print(f"shuffle = {cards}")示例3:datetime模块(日期时间)
import datetime
# 获取当前时间
now = datetime.datetime.now()
print(f"当前时间:{now}")
print(f"年:{now.year}")
print(f"月:{now.month}")
print(f"日:{now.day}")
# 创建日期
birthday = datetime.date(2000, 1, 1)
print(f"生日:{birthday}")
# 时间差
delta = datetime.timedelta(days=7)
future = now + delta
print(f"一周后:{future}")示例4:string模块(字符串操作)
import string
# 字符串常量
print(f"小写字母:{string.ascii_lowercase}")
print(f"大写字母:{string.ascii_uppercase}")
print(f"所有字母:{string.ascii_letters}")
print(f"数字:{string.digits}")
print(f"标点符号:{string.punctuation}")
# 使用示例
import random
password = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
print(f"随机密码:{password}")四、模块的属性
常用模块属性
import math
# 查看模块文档
print(f"文档字符串:{math.__doc__[:50]}...")
# 查看模块文件路径
print(f"文件路径:{math.__file__}")
# 查看模块名称
print(f"模块名称:{math.__name__}")
# 查看模块中的所有名称
print(f"模块内容(前10个):{dir(math)[:10]}")查看模块帮助
import math
# 查看模块帮助
# help(math) # 会显示详细帮助信息
# 查看特定函数的帮助
# help(math.sqrt)五、导入的注意事项
注意1:避免循环导入
# ❌ 错误:循环导入
# module_a.py
# import module_b
# module_b.py
# import module_a
# ✅ 正确:重构代码,避免循环依赖注意2:谨慎使用from...import *
# ❌ 不好的做法
from math import *
# 可能覆盖已有变量
print = "Hello" # 这会覆盖print函数
# ✅ 好的做法:明确导入需要的内容
from math import pi, sqrt注意3:导入顺序
# ✅ 推荐的导入顺序
# 1. 标准库
import math
import random
# 2. 第三方库
# import numpy
# 3. 本地模块
# import mymodule注意4:避免重复导入
import math
# 重复导入(Python会自动避免)
import math # 不会重复加载
# 检查模块是否已导入
import sys
print(f"math是否已加载:{'math' in sys.modules}")六、实际应用案例
案例1:计算器程序
import math
def calculate(expression):
"""
计算数学表达式
参数:
expression: 数学表达式字符串
返回:
计算结果
"""
try:
# 允许使用math模块的函数
result = eval(expression, {"__builtins__": None},
{"math": math, "sqrt": math.sqrt, "pow": math.pow})
return result
except Exception as e:
return f"错误:{e}"
# 使用示例
print(calculate("math.sqrt(16)")) # 输出:4.0
print(calculate("math.pow(2, 3)")) # 输出:8.0
print(calculate("math.pi * 2")) # 输出:6.283...案例2:随机密码生成器
import random
import string
def generate_password(length=12, use_symbols=True):
"""生成随机密码"""
chars = string.ascii_letters + string.digits
if use_symbols:
chars += string.punctuation
return ''.join(random.choices(chars, k=length))
# 使用示例
print(generate_password()) # 生成12位密码
print(generate_password(16, False)) # 生成16位不含符号的密码案例3:日期时间工具
import datetime
def get_weekday(date_str):
"""获取星期几"""
date = datetime.datetime.strptime(date_str, "%Y-%m-%d")
weekdays = ["星期一", "星期二", "星期三", "星期四",
"星期五", "星期六", "星期日"]
return weekdays[date.weekday()]
# 使用示例
print(get_weekday("2024-01-01")) # 输出:星期一
print(get_weekday("2024-12-25")) # 输出:星期三七、最佳实践
实践1:合理使用别名
# ✅ 常用模块的别名
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math as m实践2:按需导入
# ✅ 只导入需要的内容
from math import sqrt, pi, sin
# 而不是
import math实践3:组织导入语句
# ✅ 将导入放在文件开头
import math
import random
# 中间可以有注释
# 然后是代码
def my_function():
pass实践4:添加文档字符串
"""
模块文档字符串
说明这个模块的用途
"""
# 然后是代码
import math八、常见错误与调试
错误1:ModuleNotFoundError
# ❌ 错误
# import nonexistent_module
# ✅ 解决:确保模块已安装或路径正确
# pip install package_name错误2:ImportError
# ❌ 错误:循环导入或依赖问题
# ✅ 解决:检查模块依赖关系错误3:AttributeError
# ❌ 错误
import math
print(math.nonexistent_function)
# ✅ 解决:使用dir()查看可用功能
import math
print("可用函数:", [name for name in dir(math) if not name.startswith("_")])调试技巧:打印模块信息
import math
# 查看模块信息
print(f"模块路径:{math.__file__}")
print(f"模块名称:{math.__name__}")
print(f"前10个属性:{dir(math)[:10]}")九、小结
| 知识点 | 说明 |
|---|---|
| 模块 | Python代码文件(.py) |
| import | 导入整个模块 |
| import...as | 导入并起别名 |
| from...import | 导入特定内容 |
| from...import* | 导入所有内容(不推荐) |
| name | 模块名称 |
| file | 模块文件路径 |
| dir() | 查看模块内容 |
十、课后练习
练习1
使用math模块计算圆的面积和周长。
练习2
使用random模块生成一个1-100的随机数并猜数字。
练习3
使用datetime模块计算两个日期之间的天数差。
练习4
使用string模块生成一个包含大小写字母和数字的随机字符串。
练习5
创建自己的模块,定义几个函数并在其他程序中使用。