11.1 模块的概念
模块是包含 Python 代码的 .py 文件,用于组织和管理代码。
为什么使用模块
- 代码复用:在多个程序中共享代码
- 命名空间:避免名称冲突
- 可维护性:将代码分解为可管理的部分
11.2 导入模块
import 语句
1 2 3 4 5
| import math
print(math.pi) print(math.sqrt(16))
|
from…import 语句
1 2 3 4 5 6 7 8
| from math import pi, sqrt
print(pi) print(sqrt(16))
from math import *
|
as 别名
1 2 3 4 5 6
| import numpy as np import pandas as pd from datetime import datetime as dt
now = dt.now() print(now)
|
11.3 标准库常用模块
os 模块 - 操作系统接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import os
print(os.getcwd())
os.chdir("/tmp")
os.makedirs("test/nested", exist_ok=True)
print(os.listdir("."))
print(os.environ.get("PATH"))
|
sys 模块 - 系统相关
1 2 3 4 5 6 7 8 9 10 11 12 13
| import sys
print(sys.argv)
print(sys.version)
print(sys.path)
|
datetime 模块 - 日期时间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| from datetime import datetime, date, time, timedelta
now = datetime.now() print(now)
print(now.strftime("%Y-%m-%d %H:%M:%S"))
dt = datetime.strptime("2024-11-22", "%Y-%m-%d") print(dt)
tomorrow = now + timedelta(days=1) print(tomorrow)
diff = tomorrow - now print(diff.days)
|
random 模块 - 随机数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import random
print(random.randint(1, 10))
print(random.random())
fruits = ["apple", "banana", "orange"] print(random.choice(fruits))
random.shuffle(fruits) print(fruits)
numbers = list(range(1, 11)) print(random.sample(numbers, 3))
|
11.4 自定义模块
创建模块
创建 mymodule.py:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
def greet(name): return f"Hello, {name}!"
def add(a, b): return a + b
PI = 3.14159
class Calculator: def multiply(self, a, b): return a * b
|
使用模块
1 2 3 4 5 6 7 8 9
| import mymodule
print(mymodule.greet("Alice")) print(mymodule.add(3, 5)) print(mymodule.PI)
calc = mymodule.Calculator() print(calc.multiply(4, 5))
|
11.5 包(Package)
包是包含多个模块的目录,通过 __init__.py 标识。
包结构
1 2 3 4 5 6 7
| mypackage/ __init__.py module1.py module2.py subpackage/ __init__.py module3.py
|
init.py 的作用
1 2 3 4 5 6 7 8 9 10
|
print("Package initialized")
from .module1 import func1 from .module2 import func2
__all__ = ["func1", "func2"]
|
导入包
1 2 3 4 5 6 7 8
| from mypackage import module1
from mypackage.module1 import func1
from mypackage import func1, func2
|
11.6 第三方包管理
pip 命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| pip install requests
pip install requests==2.28.0
pip install --upgrade requests
pip uninstall requests
pip list
pip freeze > requirements.txt
pip install -r requirements.txt
|
requirements.txt 示例
1 2 3 4
| requests==2.31.0 flask==3.0.0 numpy>=1.24.0 pandas~=2.1.0
|
11.7 虚拟环境
虚拟环境用于隔离项目依赖。
创建虚拟环境
1 2 3 4 5 6 7 8 9 10 11
| python -m venv myenv
myenv\Scripts\activate
source myenv/bin/activate
deactivate
|
使用虚拟环境
1 2 3 4 5
| pip install requests
pip list
|
11.8 name 属性
1 2 3 4 5 6 7
|
def main(): print("Module is running directly")
if __name__ == "__main__": main()
|
- 直接运行:
__name__ 是 "__main__"
- 被导入:
__name__ 是模块名
11.9 本章小结
- 模块是
.py 文件,包是包含 __init__.py 的目录
- 导入方式:
import、from...import、as 别名
- 标准库:
os、sys、datetime、random 等
- 使用
pip 管理第三方包
- 虚拟环境隔离项目依赖
__name__ == "__main__" 用于判断直接运行
练习题
- 创建一个模块
calculator.py,包含加减乘除函数
- 使用
datetime 模块计算两个日期之间的天数
- 使用
random 模块生成 6 位随机验证码
- 创建虚拟环境并安装
requests 包