【面试宝典】Python 全栈面试实战
实验环境 :华为云 ECS 服务器 ecs-5d9b-0001 (119.8.30.110) 操作系统 :Ubuntu 24.04.4 LTS (Linux 6.8.0-106-generic) Python版本 :3.12.3 实验时间 :2026-07-05 实验方式:所有代码均在 ECS 服务器上真实上机运行
目录
| 序号 | 章节 | 知识点 |
|---|---|---|
| 01 | [Python 数据类型](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试 "#01-python-%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B") | 数据类型创建与操作、面试题 |
| 02 | [Python 函数和高阶函数](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试 "#02-python-%E5%87%BD%E6%95%B0%E5%92%8C%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0") | 函数定义、高阶函数、装饰器 |
| 03 | [Python 包与模块、异常处理](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试 "#03-python-%E5%8C%85%E4%B8%8E%E6%A8%A1%E5%9D%97%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86") | 模块导入、异常处理机制 |
| 04 | [Python 面向对象](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试 "#04-python-%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1") | OOP三大特性、魔术方法、内存管理 |
| 05 | [Python 并发编程](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试 "#05-python-%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B") | 线程、协程、锁、GIL |
| 06 | [Python 设计模式](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试 "#06-python-%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F") | 单例、工厂、装饰器、观察者等 |
| 07 | [Python 数据库](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试 "#07-python-%E6%95%B0%E6%8D%AE%E5%BA%93") | SQLite/Redis/MongoDB |
| 08 | [Python Web 框架](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试 "#08-python-web-%E6%A1%86%E6%9E%B6") | Flask/Django/FastAPI |
| 09 | [Python 爬虫](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试 "#09-python-%E7%88%AC%E8%99%AB") | HTTP请求、HTML解析、数据存储 |
| 10 | [Python 自动化测试](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试 "#10-python-%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95") | unittest/Mock/接口测试/Web测试 |
服务器环境信息
makefile
主机名: ecs-5d9b-0001
操作系统: Ubuntu 24.04.4 LTS
内核: Linux 6.8.0-106-generic x86_64
Python: 3.12.3
CPU: 8vCPUs (c6s.2xlarge.2)
内存: 16GiB
弹性公网IP: 119.8.30.110
私有IP: 192.168.0.186
03 Python 包与模块、异常处理
知识点
1.Python中包与模块的定义以及常见模块的的使用 2.Python中异常的处理
简介
模块和包是Python代码组织的基本方式。异常处理是保证程序健壮性的关键机制,Python提供了try-except-else-finally完整结构和自定义异常能力。
实验源码
python
#!/usr/bin/env python3
"""
【面试宝典】Python 包与模块、异常处理
知识点: 1.Python中包与模块的定义以及常见模块的的使用 2.Python中异常的处理
"""
print("=" * 70)
print("【面试宝典】Python 包与模块、异常处理")
print("=" * 70)
# ============================================================
# 1. 模块与包
# ============================================================
print("\n" + "=" * 70)
print("1. 模块与包")
print("=" * 70)
# 1.1 模块导入方式
print("\n--- 1.1 模块导入方式 ---")
import os
import sys
import json
from datetime import datetime, timedelta
from collections import OrderedDict, namedtuple, deque
import math
print(f"os.name = {os.name}")
print(f"sys.platform = {sys.platform}")
print(f"sys.version = {sys.version.split()[0]}")
print(f"datetime.now() = {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# 1.2 __name__ == "__main__"
print("\n--- 1.2 __name__ == '__main__' ---")
print(f"当前模块 __name__ = '{__name__}'")
print("当直接运行脚本时 __name__ 为 '__main__'")
print("当被导入时 __name__ 为模块名")
# 1.3 __file__ 和模块路径
print("\n--- 1.3 模块路径 ---")
print(f"sys.path 前5项:")
for i, p in enumerate(sys.path[:5]):
print(f" [{i}] {p}")
# 1.4 常见标准库
print("\n--- 1.4 常见标准库 ---")
# os模块
print("\nos模块:")
print(f" os.getcwd() = {os.getcwd()}")
print(f" os.listdir('.') 前5个: {os.listdir('.')[:5]}")
print(f" os.path.join('a', 'b', 'c') = {os.path.join('a', 'b', 'c')}")
print(f" os.path.exists('.') = {os.path.exists('.')}")
# sys模块
print("\nsys模块:")
print(f" sys.argv = {sys.argv}")
print(f" sys.maxsize = {sys.maxsize}")
# math模块
print("\nmath模块:")
print(f" math.pi = {math.pi}")
print(f" math.e = {math.e}")
print(f" math.sqrt(16) = {math.sqrt(16)}")
print(f" math.ceil(3.2) = {math.ceil(3.2)}")
print(f" math.floor(3.8) = {math.floor(3.8)}")
print(f" math.factorial(5) = {math.factorial(5)}")
print(f" math.gcd(12, 18) = {math.gcd(12, 18)}")
# json模块
print("\njson模块:")
data = {"name": "Alice", "age": 30, "scores": [90, 85, 92]}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(f" json.dumps: {json_str[:50]}...")
parsed = json.loads(json_str)
print(f" json.loads: {parsed}")
# datetime模块
print("\ndatetime模块:")
now = datetime.now()
print(f" datetime.now() = {now}")
yesterday = now - timedelta(days=1)
print(f" 昨天 = {yesterday.strftime('%Y-%m-%d')}")
tomorrow = now + timedelta(days=1)
print(f" 明天 = {tomorrow.strftime('%Y-%m-%d')}")
# collections模块
print("\ncollections模块:")
# namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(f" namedtuple Point: {p}, x={p.x}, y={p.y}")
# deque
dq = deque([1, 2, 3], maxlen=5)
dq.appendleft(0)
dq.append(4)
print(f" deque: {dq}")
# OrderedDict (Python 3.7+ dict保持插入顺序)
od = OrderedDict([('c', 3), ('a', 1), ('b', 2)])
print(f" OrderedDict: {list(od.keys())}")
# itertools模块
print("\nitertools模块:")
from itertools import chain, combinations, permutations, product
# chain - 连接多个迭代器
chained = list(chain([1, 2], [3, 4], [5]))
print(f" chain([1,2],[3,4],[5]) = {chained}")
# combinations - 组合
comb = list(combinations([1, 2, 3, 4], 2))
print(f" combinations([1,2,3,4], 2) = {comb}")
# permutations - 排列
perm = list(permutations([1, 2, 3], 2))
print(f" permutations([1,2,3], 2) = {perm}")
# product - 笛卡尔积
prod = list(product([1, 2], ['a', 'b']))
print(f" product([1,2], ['a','b']) = {prod}")
# 1.5 自定义包结构
print("\n--- 1.5 包的结构 ---")
print("""
my_package/
├── __init__.py # 包初始化文件
├── module_a.py # 模块A
├── module_b.py # 模块B
└── subpackage/
├── __init__.py
└── module_c.py # 模块C
""")
# 1.6 __init__.py 的作用
print("--- 1.6 __init__.py 的作用 ---")
print("1. 标识一个目录是Python包")
print("2. 执行包的初始化代码")
print("3. 控制 from package import * 的行为 (通过 __all__)")
print("4. Python 3.3+ 支持命名空间包(不需要__init__.py)")
# 1.7 相对导入和绝对导入
print("\n--- 1.7 导入方式 ---")
print("绝对导入: from my_package.module_a import func")
print("相对导入: from .module_a import func (当前包)")
print(" from ..module_a import func (上级包)")
# ============================================================
# 2. 异常处理
# ============================================================
print("\n" + "=" * 70)
print("2. 异常处理")
print("=" * 70)
# 2.1 基本异常处理
print("\n--- 2.1 try-except基本结构 ---")
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"捕获 ZeroDivisionError: {e}")
try:
nums = [1, 2, 3]
print(nums[10])
except IndexError as e:
print(f"捕获 IndexError: {e}")
try:
d = {"a": 1}
print(d["b"])
except KeyError as e:
print(f"捕获 KeyError: {e}")
# 2.2 多个except
print("\n--- 2.2 多个except子句 ---")
def safe_divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
return "错误: 除数不能为零"
except TypeError:
return "错误: 类型不匹配"
except Exception as e:
return f"未知错误: {e}"
print(f"safe_divide(10, 2) = {safe_divide(10, 2)}")
print(f"safe_divide(10, 0) = {safe_divide(10, 0)}")
print(f"safe_divide('10', 2) = {safe_divide('10', 2)}")
# 2.3 try-except-else-finally
print("\n--- 2.3 try-except-else-finally 完整结构 ---")
def read_file_demo(filename):
try:
f = open(filename, 'r')
content = f.read()
except FileNotFoundError:
print(f" 文件不存在: {filename}")
except PermissionError:
print(f" 权限不足: {filename}")
else:
print(f" 文件读取成功, 长度: {len(content)} 字符")
return content
finally:
print(f" finally: 总是执行(清理资源)")
try:
f.close()
except:
pass
read_file_demo("/etc/hostname")
read_file_demo("/nonexistent/file.txt")
# 2.4 主动抛出异常
print("\n--- 2.4 raise 主动抛出异常 ---")
def validate_age(age):
if not isinstance(age, int):
raise TypeError(f"age必须是整数, 得到 {type(age).__name__}")
if age < 0 or age > 150:
raise ValueError(f"age必须在0-150之间, 得到 {age}")
return age
try:
validate_age(-5)
except ValueError as e:
print(f" ValueError: {e}")
try:
validate_age("twenty")
except TypeError as e:
print(f" TypeError: {e}")
# 2.5 自定义异常
print("\n--- 2.5 自定义异常 ---")
class AppError(Exception):
"""应用基础异常"""
pass
class DatabaseError(AppError):
"""数据库异常"""
def __init__(self, message, error_code=None):
super().__init__(message)
self.error_code = error_code
class NetworkError(AppError):
"""网络异常"""
pass
def connect_db(host):
if not host:
raise DatabaseError("数据库主机不能为空", error_code=4001)
try:
connect_db("")
except DatabaseError as e:
print(f" 捕获 DatabaseError: {e}, error_code={e.error_code}")
# 异常继承链
print(f"\n DatabaseError -> AppError -> Exception: {issubclass(DatabaseError, Exception)}")
print(f" NetworkError -> AppError -> Exception: {issubclass(NetworkError, Exception)}")
# 2.6 异常链 (Python 3+)
print("\n--- 2.6 异常链 (raise from) ---")
def process_data(data):
try:
return json.loads(data)
except json.JSONDecodeError as e:
raise ValueError("数据处理失败") from e
try:
process_data("{invalid json}")
except ValueError as e:
print(f" ValueError: {e}")
print(f" 原始异常: {e.__cause__}")
# 2.7 assert断言
print("\n--- 2.7 assert断言 ---")
def calculate_bmi(weight, height):
assert weight > 0, "体重必须大于0"
assert height > 0, "身高必须大于0"
return weight / (height ** 2)
try:
calculate_bmi(-70, 1.75)
except AssertionError as e:
print(f" AssertionError: {e}")
# 2.8 contextlib.suppress
print("\n--- 2.8 contextlib.suppress ---")
from contextlib import suppress
with suppress(FileNotFoundError):
open("/nonexistent/file.txt", "r")
print(" 这行不会执行")
print(" suppress后的代码正常执行")
# 2.9 常见异常类型
print("\n--- 2.9 常见异常类型 ---")
common_exceptions = [
("TypeError", "类型错误"),
("ValueError", "值错误"),
("IndexError", "索引越界"),
("KeyError", "字典键不存在"),
("AttributeError", "属性不存在"),
("NameError", "变量名未定义"),
("ZeroDivisionError", "除以零"),
("FileNotFoundError", "文件不存在"),
("ImportError", "导入失败"),
("StopIteration", "迭代器耗尽"),
("RuntimeError", "运行时错误"),
("RecursionError", "递归过深"),
("KeyboardInterrupt", "键盘中断(Ctrl+C)"),
("MemoryError", "内存不足"),
("OverflowError", "数值溢出"),
]
for name, desc in common_exceptions:
print(f" {name:25s} - {desc}")
# 2.10 with语句和上下文管理器
print("\n--- 2.10 with语句和上下文管理器 ---")
# 自定义上下文管理器
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
print(f" __enter__: 打开文件 {self.filename}")
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
print(f" __exit__: 关闭文件 (异常: {exc_type.__name__ if exc_type else 'None'})")
if self.file:
self.file.close()
return False # 不抑制异常
# 使用contextlib
from contextlib import contextmanager
@contextmanager
def timer_context(name):
start = time.time()
try:
yield
finally:
elapsed = time.time() - start
print(f" [{name}] 耗时: {elapsed:.6f}s")
import time as time_module
with timer_context("计算"):
total = sum(range(1000000))
print(f" 计算结果: {total}")
# 2.11 traceback模块
print("\n--- 2.11 traceback模块 ---")
import traceback
def func_c():
raise ValueError("来自func_c的错误")
def func_b():
func_c()
def func_a():
func_b()
try:
func_a()
except ValueError:
print(" 完整调用栈:")
tb_lines = traceback.format_exc().split('\n')
for line in tb_lines:
if line.strip():
print(f" {line}")
print("\n" + "=" * 70)
print("包与模块、异常处理实验完成!")
print("=" * 70)
上机输出(ECS服务器实际运行结果)
lua
======================================================================
【面试宝典】Python 包与模块、异常处理
======================================================================
======================================================================
1. 模块与包
======================================================================
--- 1.1 模块导入方式 ---
os.name = posix
sys.platform = linux
sys.version = 3.12.3
datetime.now() = 2026-07-05 21:14:18
--- 1.2 __name__ == '__main__' ---
当前模块 __name__ = '__main__'
当直接运行脚本时 __name__ 为 '__main__'
当被导入时 __name__ 为模块名
--- 1.3 模块路径 ---
sys.path 前5项:
[0] /root/interview
[1] /usr/lib/python312.zip
[2] /usr/lib/python3.12
[3] /usr/lib/python3.12/lib-dynload
[4] /usr/local/lib/python3.12/dist-packages
--- 1.4 常见标准库 ---
os模块:
os.getcwd() = /root/interview
os.listdir('.') 前5个: ['exp04_oop.py', 'exp03_modules_exceptions.py', 'exp02_functions.py', 'exp06_design_patterns.py', 'exp07_database.py']
os.path.join('a', 'b', 'c') = a/b/c
os.path.exists('.') = True
sys模块:
sys.argv = ['exp03_modules_exceptions.py']
sys.maxsize = 9223372036854775807
math模块:
math.pi = 3.141592653589793
math.e = 2.718281828459045
math.sqrt(16) = 4.0
math.ceil(3.2) = 4
math.floor(3.8) = 3
math.factorial(5) = 120
math.gcd(12, 18) = 6
json模块:
json.dumps: {
"name": "Alice",
"age": 30,
"scores": [
...
json.loads: {'name': 'Alice', 'age': 30, 'scores': [90, 85, 92]}
datetime模块:
datetime.now() = 2026-07-05 21:14:18.468985
昨天 = 2026-07-04
明天 = 2026-07-06
collections模块:
namedtuple Point: Point(x=3, y=4), x=3, y=4
deque: deque([0, 1, 2, 3, 4], maxlen=5)
OrderedDict: ['c', 'a', 'b']
itertools模块:
chain([1,2],[3,4],[5]) = [1, 2, 3, 4, 5]
combinations([1,2,3,4], 2) = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
permutations([1,2,3], 2) = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
product([1,2], ['a','b']) = [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
--- 1.5 包的结构 ---
my_package/
├── __init__.py # 包初始化文件
├── module_a.py # 模块A
├── module_b.py # 模块B
└── subpackage/
├── __init__.py
└── module_c.py # 模块C
--- 1.6 __init__.py 的作用 ---
1. 标识一个目录是Python包
2. 执行包的初始化代码
3. 控制 from package import * 的行为 (通过 __all__)
4. Python 3.3+ 支持命名空间包(不需要__init__.py)
--- 1.7 导入方式 ---
绝对导入: from my_package.module_a import func
相对导入: from .module_a import func (当前包)
from ..module_a import func (上级包)
======================================================================
2. 异常处理
======================================================================
--- 2.1 try-except基本结构 ---
捕获 ZeroDivisionError: division by zero
捕获 IndexError: list index out of range
捕获 KeyError: 'b'
--- 2.2 多个except子句 ---
safe_divide(10, 2) = 5.0
safe_divide(10, 0) = 错误: 除数不能为零
safe_divide('10', 2) = 错误: 类型不匹配
--- 2.3 try-except-else-finally 完整结构 ---
文件读取成功, 长度: 14 字符
finally: 总是执行(清理资源)
文件不存在: /nonexistent/file.txt
finally: 总是执行(清理资源)
--- 2.4 raise 主动抛出异常 ---
ValueError: age必须在0-150之间, 得到 -5
TypeError: age必须是整数, 得到 str
--- 2.5 自定义异常 ---
捕获 DatabaseError: 数据库主机不能为空, error_code=4001
DatabaseError -> AppError -> Exception: True
NetworkError -> AppError -> Exception: True
--- 2.6 异常链 (raise from) ---
ValueError: 数据处理失败
原始异常: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
--- 2.7 assert断言 ---
AssertionError: 体重必须大于0
--- 2.8 contextlib.suppress ---
suppress后的代码正常执行
--- 2.9 常见异常类型 ---
TypeError - 类型错误
ValueError - 值错误
IndexError - 索引越界
KeyError - 字典键不存在
AttributeError - 属性不存在
NameError - 变量名未定义
ZeroDivisionError - 除以零
FileNotFoundError - 文件不存在
ImportError - 导入失败
StopIteration - 迭代器耗尽
RuntimeError - 运行时错误
RecursionError - 递归过深
KeyboardInterrupt - 键盘中断(Ctrl+C)
MemoryError - 内存不足
OverflowError - 数值溢出
--- 2.10 with语句和上下文管理器 ---
Traceback (most recent call last):
File "/root/interview/exp03_modules_exceptions.py", line 354, in <module>
with timer_context("计算"):
File "/usr/lib/python3.12/contextlib.py", line 137, in __enter__
return next(self.gen)
^^^^^^^^^^^^^^
File "/root/interview/exp03_modules_exceptions.py", line 346, in timer_context
start = time.time()
^^^^
NameError: name 'time' is not defined. Did you forget to import 'time'?