Python知识体系大纲

Python核心知识体系大纲

1. 基础语法

1.1 变量与数据类型

1
2
3
4
5
6
7
8
9
10
# 基本类型示例
age = 25 # int
price = 19.99 # float
name = "Alice" # str
is_valid = True # bool
data = None # NoneType

# 类型转换
num_str = "123"
real_num = int(num_str) # 字符串转整数

应用场景:基础数据处理、配置参数存储
练习:创建一个包含不同数据类型的字典,存储商品信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
product = {
"product_id":1001,
"name":"自动铅笔",
"price": 89.99, # float 商品价格
"in_stock": True, # bool 库存状态
"specifications": [ # list 规格参数
"Bluetooth 5.0",
"2.4GHz USB",
"2400DPI"
],
"color_options": ("Black", "White"), # tuple 可选颜色
"promotion": { # dict 促销信息
"type": "seasonal",
"discount": 0.15
},
"last_updated": "2023-08-20", # str 日期字符串
"accessories": None
}


2. 数据结构

2.1 列表(List)

1
2
3
4
5
6
7
8
# 列表操作
fruits = ["apple", "banana"]
fruits.append("orange") # 追加元素
sliced = fruits[1:] # 切片操作
matrix = [[1,2], [3,4]] # 二维列表

# 列表推导式
squares = [x**2 for x in range(10)]

应用场景:数据收集、临时存储
练习:使用列表推导式生成斐波那契数列前20项

1
2
3
4
5
6
7
8
# 使用闭式公式的列表推导式实现
import math

phi = (1 + math.sqrt(5)) / 2 # 黄金分割比例
fibonacci = [int((phi**n - (1-phi)**n)/math.sqrt(5)) for n in range(20)]

print(fibonacci) # 输出结果:[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]

2.2 字典(Dict)

1
2
3
4
5
6
7
# 字典操作
user = {"name": "Bob", "age": 30}
user["email"] = "bob@example.com" # 添加键值对
keys = user.keys() # 获取所有键

# 字典推导式
square_dict = {x: x*x for x in range(5)}

应用场景:配置管理、JSON数据处理
练习:统计文本中各单词出现频率


3. 函数编程

3.1 函数定义

1
2
3
4
5
6
7
8
9
# 带类型提示的函数
def calculate_tax(income: float) -> float:
"""计算所得税"""
if income > 10000:
return income * 0.2
return income * 0.1

# lambda函数
add = lambda x, y: x + y

应用场景:代码复用、模块化开发
练习:编写递归函数实现阶乘计算


4. 面向对象编程

4.1 类与继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
raise NotImplementedError

class Dog(Animal):
def speak(self):
return "Woof!"

# 使用示例
buddy = Dog("Buddy")
print(buddy.speak()) # 输出: Woof!

应用场景:GUI开发、游戏实体建模
练习:实现一个银行账户类,包含存取款方法


5. 模块与包

5.1 模块化开发

1
2
3
4
5
6
7
8
9
10
11
12
13
# 模块导入方式
import math
from datetime import datetime
import numpy as np

# 创建包结构
"""
my_package/
├── __init__.py
├── utils.py
└── core/
└── processor.py
"""

应用场景:大型项目组织、代码复用
练习:创建自定义数学工具包


6. 文件操作

6.1 文本文件处理

1
2
3
4
5
6
7
8
9
10
# 上下文管理器处理文件
with open("data.txt", "r", encoding="utf-8") as f:
lines = f.readlines()

# CSV文件处理
import csv
with open("data.csv") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"])

应用场景:日志处理、数据导入导出
练习:实现CSV到JSON格式转换器


7. 异常处理

1
2
3
4
5
6
7
8
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print("运算成功")
finally:
print("清理资源")

应用场景:网络请求容错、文件操作保护
练习:为文件读取添加多重异常捕获


8. 高级特性

8.1 装饰器

1
2
3
4
5
6
7
8
9
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper

@logger
def add(a, b):
return a + b

应用场景:日志记录、权限验证
练习:实现执行时间统计装饰器


9. 常用标准库

9.1 并发编程

1
2
3
4
5
6
7
8
# 线程池示例
from concurrent.futures import ThreadPoolExecutor

def task(n):
return n * n

with ThreadPoolExecutor() as executor:
results = executor.map(task, range(10))

应用场景:Web爬虫、批量数据处理
练习:实现多线程文件下载器


10. 项目组织

10.1 虚拟环境

1
2
3
4
5
# 创建虚拟环境
python -m venv myenv

# 依赖管理
pip install -r requirements.txt

应用场景:多项目依赖隔离
练习:为项目配置标准化开发环境


知识图谱