1. Python语言概述与核心特性
Python作为一门诞生于1991年的高级编程语言,其设计哲学强调代码可读性和简洁性。与其他语言相比,Python最显著的特征是使用缩进来划分代码块,而非传统的大括号。这种设计选择使得Python代码具有天然的整洁性和一致性。
提示:Python的缩进规则不是可选项,而是语法要求。通常建议使用4个空格作为标准缩进量,这已经成为PEP 8(Python增强提案)的官方推荐。
Python采用动态类型系统和自动内存管理,这意味着开发者无需声明变量类型,也无需手动分配和释放内存。这种特性大幅降低了初学者的学习门槛。例如,在Python中声明变量就像在记事本上写便签一样简单:
python复制message = "Hello World" # 字符串类型自动推断
count = 42 # 整数类型自动推断
pi = 3.14159 # 浮点数类型自动推断
Python解释器在执行时会自动进行类型检查,这种动态特性使得代码编写更加灵活。但这也带来了一定的运行时风险,因此现代的Python开发通常会结合类型提示(Type Hints)来提高代码可靠性:
python复制def greet(name: str) -> str:
return f"Hello, {name}"
2. 开发环境搭建与工具链配置
2.1 Python解释器安装
对于Windows用户,建议通过官方安装程序进行安装。安装时务必勾选"Add Python to PATH"选项,这将允许你在任何目录下通过命令行运行Python。macOS用户通常已经预装了Python 2.7,但建议通过Homebrew安装最新版本:
bash复制brew install python
验证安装是否成功:
bash复制python --version
# 或对于Python 3.x
python3 --version
2.2 虚拟环境管理
Python的虚拟环境(virtual environment)是项目隔离的最佳实践。它允许每个项目拥有独立的依赖库,避免版本冲突。创建和使用虚拟环境的流程如下:
bash复制# 创建虚拟环境
python -m venv myenv
# 激活虚拟环境(Windows)
myenv\Scripts\activate
# 激活虚拟环境(macOS/Linux)
source myenv/bin/activate
# 安装项目依赖
pip install requests pandas
# 冻结依赖版本
pip freeze > requirements.txt
2.3 开发工具选择
VS Code是目前最受欢迎的Python开发环境之一,其配置要点包括:
- 安装Python扩展(ms-python.python)
- 配置Python解释器路径(Ctrl+Shift+P → "Python: Select Interpreter")
- 启用代码格式化(推荐使用autopep8或black)
- 设置代码检查工具(pylint或flake8)
对于大型项目,PyCharm Professional提供了更强大的专业功能,如数据库工具、科学模式等。社区版虽然免费,但功能有所限制。
3. Python基础语法精要
3.1 变量与数据类型
Python中的基本数据类型包括:
- 数字类型:int, float, complex
- 序列类型:str, list, tuple
- 映射类型:dict
- 集合类型:set, frozenset
- 布尔类型:bool
类型转换示例:
python复制num_str = "123"
num_int = int(num_str) # 字符串转整数
num_float = float(num_str) # 字符串转浮点数
str_num = str(123) # 数字转字符串
3.2 控制结构
条件判断采用if-elif-else结构:
python复制age = 18
if age < 13:
print("Child")
elif 13 <= age < 18:
print("Teenager")
else:
print("Adult")
循环结构包括while和for两种形式:
python复制# while循环示例
count = 0
while count < 5:
print(count)
count += 1
# for循环示例
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
3.3 函数定义与调用
Python函数使用def关键字定义,支持多种参数传递方式:
python复制def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
# 位置参数
print(greet("Alice")) # 输出: Hello, Alice!
# 关键字参数
print(greet(name="Bob", greeting="Hi")) # 输出: Hi, Bob!
# 可变参数
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 2, 3)) # 输出: 6
4. 常用数据结构操作
4.1 列表(List)操作
列表是Python中最常用的可变序列类型,支持丰富的操作方法:
python复制# 创建列表
numbers = [1, 2, 3, 4, 5]
# 切片操作
first_two = numbers[:2] # [1, 2]
last_three = numbers[-3:] # [3, 4, 5]
# 列表推导式
squares = [x**2 for x in numbers] # [1, 4, 9, 16, 25]
# 常用方法
numbers.append(6) # 添加元素
numbers.insert(0, 0) # 在指定位置插入
numbers.remove(3) # 删除第一个匹配项
popped = numbers.pop() # 移除并返回最后一个元素
4.2 字典(Dict)操作
字典是键值对的集合,提供高效的数据查找:
python复制# 创建字典
person = {
"name": "Alice",
"age": 25,
"occupation": "Engineer"
}
# 访问元素
name = person["name"] # "Alice"
age = person.get("age") # 25
# 更新字典
person["age"] = 26 # 更新值
person["city"] = "New York" # 添加新键值对
# 字典遍历
for key, value in person.items():
print(f"{key}: {value}")
# 字典推导式
squared_dict = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
4.3 集合(Set)操作
集合用于存储唯一元素,支持数学集合运算:
python复制# 创建集合
primes = {2, 3, 5, 7}
evens = {2, 4, 6, 8}
# 集合运算
union = primes | evens # 并集 {2, 3, 4, 5, 6, 7, 8}
intersection = primes & evens # 交集 {2}
difference = primes - evens # 差集 {3, 5, 7}
5. 文件操作与异常处理
5.1 文件读写
Python使用内置的open函数进行文件操作:
python复制# 写入文件
with open("example.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("This is a text file.\n")
# 读取文件
with open("example.txt", "r", encoding="utf-8") as f:
content = f.read() # 读取全部内容
lines = f.readlines() # 按行读取为列表
# 追加内容
with open("example.txt", "a", encoding="utf-8") as f:
f.write("Adding new line at the end.\n")
5.2 异常处理机制
Python使用try-except块处理异常:
python复制try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error occurred: {e}")
result = float('inf') # 设置默认值
except (TypeError, ValueError) as e:
print(f"Type or value error: {e}")
else:
print("Operation succeeded")
finally:
print("This always executes")
自定义异常示例:
python复制class MyCustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def validate_age(age):
if age < 0:
raise MyCustomError("Age cannot be negative")
return age
try:
validate_age(-5)
except MyCustomError as e:
print(f"Validation failed: {e}")
6. 模块与包管理
6.1 模块导入系统
Python的模块系统允许代码组织和复用:
python复制# 导入整个模块
import math
print(math.sqrt(16)) # 4.0
# 导入特定功能
from datetime import datetime
print(datetime.now())
# 别名导入
import numpy as np
import pandas as pd
# 相对导入(在包内部)
from . import submodule
from .. import parent_module
6.2 包创建与发布
一个标准的Python包目录结构如下:
code复制mypackage/
├── __init__.py
├── module1.py
├── module2.py
└── tests/
└── test_module1.py
setup.py是打包的核心配置文件:
python复制from setuptools import setup, find_packages
setup(
name="mypackage",
version="0.1",
packages=find_packages(),
install_requires=[
'requests>=2.25.1',
'numpy>=1.20.0'
],
python_requires='>=3.6',
)
发布到PyPI的流程:
- 构建分发包:
python setup.py sdist bdist_wheel - 上传到PyPI:
twine upload dist/*
7. 面向对象编程
7.1 类与对象
Python中的类定义和实例化:
python复制class Person:
# 类属性
species = "Homo sapiens"
# 初始化方法
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 实例方法
def greet(self):
return f"Hello, my name is {self.name}"
# 类方法
@classmethod
def from_birth_year(cls, name, birth_year):
age = datetime.now().year - birth_year
return cls(name, age)
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 创建实例
person1 = Person("Alice", 25)
person2 = Person.from_birth_year("Bob", 1990)
print(person1.greet()) # Hello, my name is Alice
print(Person.is_adult(20)) # True
7.2 继承与多态
Python支持多重继承和方法重写:
python复制class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this method")
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# 多态示例
animals = [Dog("Rex"), Cat("Whiskers")]
for animal in animals:
print(animal.speak())
7.3 特殊方法与运算符重载
通过特殊方法可以实现运算符重载:
python复制class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 4)
v2 = Vector(1, 3)
print(v1 + v2) # Vector(3, 7)
print(v1 * 3) # Vector(6, 12)
8. 常用标准库模块
8.1 os与sys模块
操作系统交互和系统参数:
python复制import os
import sys
# 文件系统操作
current_dir = os.getcwd() # 获取当前目录
os.makedirs("new_dir", exist_ok=True) # 创建目录
files = os.listdir(".") # 列出目录内容
# 系统参数
script_path = sys.argv[0] # 脚本路径
python_path = sys.executable # Python解释器路径
module_search_path = sys.path # 模块搜索路径
8.2 datetime与time模块
日期和时间处理:
python复制from datetime import datetime, timedelta
import time
# 当前时间
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 格式化输出
# 时间计算
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
# 时间戳
timestamp = time.time() # 当前时间戳
local_time = time.localtime(timestamp) # 本地时间结构
8.3 json与pickle模块
数据序列化:
python复制import json
import pickle
# JSON序列化
data = {"name": "Alice", "age": 25, "hobbies": ["reading", "hiking"]}
json_str = json.dumps(data) # 转为JSON字符串
loaded_data = json.loads(json_str) # 从字符串加载
# 文件操作
with open("data.json", "w") as f:
json.dump(data, f)
# pickle序列化(Python专用)
binary_data = pickle.dumps(data) # 转为字节串
original_data = pickle.loads(binary_data)
9. 第三方库生态
9.1 数据处理与分析
Pandas是数据分析的核心库:
python复制import pandas as pd
# 创建DataFrame
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"City": ["NY", "LA", "Chicago"]
}
df = pd.DataFrame(data)
# 数据操作
filtered = df[df["Age"] > 28] # 筛选
grouped = df.groupby("City")["Age"].mean() # 分组聚合
sorted_df = df.sort_values("Age", ascending=False) # 排序
9.2 网络请求与Web开发
Requests库简化HTTP请求:
python复制import requests
# GET请求
response = requests.get("https://api.github.com/events")
events = response.json() # 解析JSON响应
# POST请求
payload = {"key1": "value1", "key2": "value2"}
response = requests.post("https://httpbin.org/post", data=payload)
print(response.status_code) # 状态码
print(response.text) # 响应内容
Flask轻量级Web框架:
python复制from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome to my Flask app!"
@app.route("/api/data", methods=["POST"])
def process_data():
data = request.json
result = {"status": "success", "received": data}
return jsonify(result)
if __name__ == "__main__":
app.run(debug=True)
9.3 科学计算与可视化
NumPy和Matplotlib组合:
python复制import numpy as np
import matplotlib.pyplot as plt
# 创建数据
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 绘制图形
plt.figure(figsize=(8, 4))
plt.plot(x, y, label="sin(x)")
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.legend()
plt.grid(True)
plt.show()
10. 性能优化与调试技巧
10.1 性能分析工具
使用cProfile进行性能分析:
python复制import cProfile
def slow_function():
total = 0
for i in range(1000000):
total += i
return total
# 性能分析
profiler = cProfile.Profile()
profiler.enable()
slow_function()
profiler.disable()
profiler.print_stats(sort="cumulative")
10.2 代码优化策略
列表操作优化示例:
python复制# 低效方式
result = []
for i in range(1000000):
result.append(i * 2)
# 高效方式1:列表推导式
result = [i * 2 for i in range(1000000)]
# 高效方式2:生成器表达式
result = (i * 2 for i in range(1000000)) # 惰性求值
10.3 调试技巧
使用pdb进行调试:
python复制import pdb
def complex_calculation(a, b):
pdb.set_trace() # 设置断点
result = 0
for i in range(a):
for j in range(b):
result += i * j
return result
# 常用pdb命令:
# n(ext) - 执行下一行
# c(ontinue) - 继续执行直到下一个断点
# p(rint) - 打印变量值
# l(ist) - 显示当前代码位置
# q(uit) - 退出调试器
11. 项目结构与代码规范
11.1 典型项目结构
一个规范的Python项目通常包含以下目录结构:
code复制project_root/
├── docs/ # 文档
├── src/ # 源代码
│ ├── package_name/ # 主包
│ │ ├── __init__.py
│ │ ├── module1.py
│ │ └── subpackage/
│ ├── tests/ # 测试代码
│ │ ├── __init__.py
│ │ └── test_module1.py
├── scripts/ # 实用脚本
├── data/ # 数据文件
├── .gitignore # Git忽略规则
├── README.md # 项目说明
├── requirements.txt # 依赖列表
├── setup.py # 打包配置
└── pyproject.toml # 构建系统配置
11.2 PEP 8编码规范
Python官方编码规范要点:
- 缩进:4个空格(不使用Tab)
- 行长度:不超过79字符(文档字符串/注释不超过72字符)
- 导入顺序:标准库→第三方库→本地应用/库,每组导入用空行分隔
- 命名约定:
- 模块名:小写字母,必要时用下划线
- 类名:驼峰式(CapWords)
- 函数/变量名:小写字母,用下划线分隔
- 常量名:全大写字母,用下划线分隔
11.3 文档字符串规范
Python使用docstring进行代码文档化:
python复制def calculate_statistics(data):
"""计算数据的统计指标
参数:
data (list): 包含数值的列表
返回:
dict: 包含以下键的字典:
- mean (float): 平均值
- median (float): 中位数
- std_dev (float): 标准差
示例:
>>> calculate_statistics([1, 2, 3, 4, 5])
{'mean': 3.0, 'median': 3.0, 'std_dev': 1.4142135623730951}
"""
n = len(data)
mean = sum(data) / n
sorted_data = sorted(data)
median = sorted_data[n//2] if n % 2 else (sorted_data[n//2-1] + sorted_data[n//2]) / 2
variance = sum((x - mean)**2 for x in data) / n
std_dev = variance ** 0.5
return {
"mean": mean,
"median": median,
"std_dev": std_dev
}
12. 测试驱动开发
12.1 unittest框架
Python内置的单元测试框架:
python复制import unittest
def add(a, b):
return a + b
class TestAddFunction(unittest.TestCase):
def test_add_integers(self):
self.assertEqual(add(1, 2), 3)
def test_add_floats(self):
self.assertAlmostEqual(add(0.1, 0.2), 0.3, places=7)
def test_add_strings(self):
self.assertEqual(add("hello", " world"), "hello world")
def test_add_type_error(self):
with self.assertRaises(TypeError):
add("hello", 5)
if __name__ == "__main__":
unittest.main()
12.2 pytest框架
更现代的测试框架,语法更简洁:
python复制# test_sample.py
import pytest
def test_add_integers():
assert add(1, 2) == 3
def test_add_floats():
assert add(0.1, 0.2) == pytest.approx(0.3)
def test_add_strings():
assert add("hello", " world") == "hello world"
def test_add_type_error():
with pytest.raises(TypeError):
add("hello", 5)
运行测试:
bash复制pytest test_sample.py -v # -v 显示详细信息
12.3 测试覆盖率
使用pytest-cov插件测量测试覆盖率:
bash复制pytest --cov=my_package tests/
生成HTML报告:
bash复制pytest --cov=my_package --cov-report=html tests/
13. 打包与分发
13.1 创建可分发的包
现代Python项目推荐使用pyproject.toml:
toml复制[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "mypackage"
version = "0.1.0"
authors = [
{name = "Your Name", email = "your.email@example.com"},
]
description = "A sample Python package"
readme = "README.md"
requires-python = ">=3.7"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
[project.urls]
Homepage = "https://github.com/username/mypackage"
13.2 构建与发布
构建分发包:
bash复制python -m build
发布到PyPI:
bash复制twine upload dist/*
13.3 可执行文件打包
使用PyInstaller创建独立可执行文件:
bash复制pip install pyinstaller
pyinstaller --onefile --windowed myscript.py
常用参数:
--onefile:打包为单个可执行文件--windowed:不显示控制台窗口(GUI应用)--add-data:添加非Python文件--icon:设置应用图标
14. 异步编程基础
14.1 asyncio基础
Python的异步编程模型:
python复制import asyncio
async def fetch_data():
print("开始获取数据")
await asyncio.sleep(2) # 模拟IO操作
print("数据获取完成")
return {"data": 123}
async def main():
task1 = asyncio.create_task(fetch_data())
task2 = asyncio.create_task(fetch_data())
print("执行其他同步操作")
# 等待任务完成
result1 = await task1
result2 = await task2
print(f"结果1: {result1}")
print(f"结果2: {result2}")
asyncio.run(main())
14.2 异步HTTP请求
使用aiohttp库:
python复制import aiohttp
import asyncio
async def fetch_url(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
"https://python.org",
"https://pypi.org",
"https://github.com"
]
tasks = [fetch_url(url) for url in urls]
results = await asyncio.gather(*tasks)
for url, content in zip(urls, results):
print(f"{url}: {len(content)} bytes")
asyncio.run(main())
14.3 异步文件IO
使用aiofiles库:
python复制import aiofiles
import asyncio
async def write_file(filename, content):
async with aiofiles.open(filename, mode='w') as f:
await f.write(content)
async def read_file(filename):
async with aiofiles.open(filename, mode='r') as f:
return await f.read()
async def main():
await write_file("example.txt", "Hello, async world!")
content = await read_file("example.txt")
print(content)
asyncio.run(main())
15. 类型提示与静态检查
15.1 基本类型提示
Python 3.5+支持的类型提示:
python复制from typing import List, Dict, Tuple, Set, Optional
def process_data(
names: List[str],
ages: Dict[str, int],
coordinates: Tuple[float, float],
flags: Set[bool],
description: Optional[str] = None
) -> bool:
"""处理数据并返回成功状态"""
if not names or not ages:
return False
print(f"Processing {len(names)} names")
print(f"First coordinate: {coordinates[0]}")
if description:
print(f"Description: {description}")
return True
15.2 高级类型提示
Python 3.9+引入的更简洁语法:
python复制def merge_dicts(
dict1: dict[str, int],
dict2: dict[str, int]
) -> dict[str, list[int]]:
"""合并两个字典,相同键的值放入列表"""
result: dict[str, list[int]] = {}
for key in dict1.keys() | dict2.keys():
values = []
if key in dict1:
values.append(dict1[key])
if key in dict2:
values.append(dict2[key])
result[key] = values
return result
15.3 静态类型检查
使用mypy进行静态类型检查:
bash复制pip install mypy
mypy your_script.py
常见mypy配置(pyproject.toml):
toml复制[tool.mypy]
python_version = "3.8"
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
check_untyped_defs = true
ignore_missing_imports = true
16. 并发与并行编程
16.1 多线程编程
使用threading模块:
python复制import threading
import time
def worker(num):
print(f"Worker {num} started")
time.sleep(1)
print(f"Worker {num} finished")
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
print("All workers completed")
16.2 多进程编程
使用multiprocessing模块:
python复制import multiprocessing
import os
def square(number):
print(f"Process {os.getpid()} calculating square of {number}")
return number * number
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
with multiprocessing.Pool() as pool:
results = pool.map(square, numbers)
print(f"Results: {results}")
16.3 线程/进程安全
使用Lock保证线程安全:
python复制import threading
counter = 0
counter_lock = threading.Lock()
def increment():
global counter
for _ in range(100000):
with counter_lock:
counter += 1
threads = []
for _ in range(10):
t = threading.Thread(target=increment)
threads.append(t)
t.start()
for t in threads:
t.join()
print(f"Final counter value: {counter}")
17. 元编程与装饰器
17.1 装饰器基础
函数装饰器示例:
python复制def timing_decorator(func):
import time
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
print(f"{func.__name__} executed in {end_time - start_time:.4f} seconds")
return result
return wrapper
@timing_decorator
def calculate_sum(n):
return sum(range(n))
print(calculate_sum(1000000))
17.2 类装饰器
类装饰器示例:
python复制def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class DatabaseConnection:
def __init__(self):
print("Initializing database connection")
conn1 = DatabaseConnection()
conn2 = DatabaseConnection()
print(conn1 is conn2) # 输出: True
17.3 元类编程
使用元类控制类创建:
python复制class Meta(type):
def __new__(cls, name, bases, namespace):
# 自动添加类名小写属性
namespace['class_name_lower'] = name.lower()
return super().__new__(cls, name, bases, namespace)
class MyClass(metaclass=Meta):
pass
print(MyClass.class_name_lower) # 输出: myclass
18. 设计模式实现
18.1 工厂模式
简单工厂实现:
python复制from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class AnimalFactory:
@staticmethod
def create_animal(animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
else:
raise ValueError(f"Unknown animal type: {animal_type}")
dog = AnimalFactory.create_animal("dog")
print(dog.speak()) # 输出: Woof!
18.2 观察者模式
事件通知系统实现:
python复制class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
if observer not in self._observers:
self._observers.append(observer)
def detach(self, observer):
try:
self._observers.remove(observer)
except ValueError:
pass
def notify(self, message):
for observer in self._observers:
observer.update(message)
class Observer:
def update(self, message):
print(f"Received message: {message}")
subject = Subject()
observer1 = Observer()
observer2 = Observer()
subject.attach(observer1)
subject.attach(observer2)
subject.notify("First notification")
subject.detach(observer1)
subject.notify("Second notification")
18.3 策略模式
可替换算法实现:
python复制from abc import ABC, abstractmethod
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount):
pass
class CreditCardPayment(PaymentStrategy):
def __init__(self, card_number, expiry_date):
self.card_number = card_number
self.expiry_date = expiry_date
def pay(self, amount):
print(f"Paid ${amount} with credit card {self.card_number[-4:]}")
class PayPalPayment(PaymentStrategy):
def __init__(self, email):
self.email = email
def pay(self, amount):
print(f"Paid ${amount} with PayPal account {self.email}")
class ShoppingCart:
def __init__(self):
self.items = []
self.payment_strategy = None
def add_item(self, item, price):
self.items.append((item, price))
def set_payment_strategy(self, strategy):
self.payment_strategy = strategy
def checkout(self):
if not self.payment_strategy:
raise ValueError("Payment strategy not set")
total = sum(price for _, price in self.items)
self.payment_strategy.pay(total)
self.items = []
cart = ShoppingCart()
cart.add_item("Book", 20)
cart.add_item("Headphones", 100)
cart.set_payment_strategy(CreditCardPayment("1234567812345678", "12/25"))
cart.checkout()
cart.add_item("Mouse", 30)
cart.set_payment_strategy(PayPalPayment("user@example.com"))
cart.checkout()
19. 安全编程实践
19.1 输入验证
防御性编程示例:
python复制import re
def validate_email(email):
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
if not re.match(pattern, email):
raise ValueError("Invalid email address")
return email
def validate_age(age):
if not isinstance(age, int) or age < 0 or age > 120:
raise ValueError("Age must be a positive integer between 0 and 120")
return age
try:
email = validate_email("user@example.com")
age = validate_age(25)
print(f"Valid email: {email}, age: {age}")
except ValueError as e:
print(f"Validation error: {e}")
19.2 密码安全
使用hashlib进行密码哈希:
python复制import hashlib
import os
def hash_password(password, salt=None):
if salt is None:
salt = os.urandom(32) # 生成随机盐值
key = hashlib.pbkdf2_hmac(
'sha256',
password.encode('utf-8'),
salt,
100000 # 迭代次数
)
return salt + key
def verify_password(stored_hash, password):
salt = stored_hash[:32]
key = stored_hash[32:]
new_hash = hash_password(password, salt)
return new_hash[32:] == key
# 使用示例
password = "secure_password123"
hashed = hash_password(password)
print(f"Stored hash: {hashed.hex()}")
input_password = "secure_password123"
print(verify_password(hashed, input_password)) # True
wrong_password = "wrong_password"
print(verify_password(hashed, wrong_password)) # False
19.3 SQL注入防护
使用参数化查询:
python复制import sqlite3
def get_user_safe(db_path, user
