阶段一:基础语法与数据结构
一、目标
熟悉 Python 基础语法规则
掌握变量、字符串、数字、列表、字典等常用数据类型
二、学习内容 & 示例
1. 变量与类型
name = "Alice"
age = 25
is_active = True
Python 是动态类型的,不用加 let 或 const。
2. 字符串操作
s = "hello world"
print(s.upper()) # "HELLO WORLD"
print(s[0:5]) # "hello"
print(f"Name: {name}") # f-string 插值
3. 数组(列表 list)
nums = [1, 2, 3]
nums.append(4)
nums[1] = 5
print(nums) # [1, 5, 3, 4
4. 字典(dict)
person = {"name": "Tom", "age": 20}
print(person["name"]) # "Tom"
person["age"] = 21
5. 条件与循环
if age > 18:
print("adult")
else:
print("minor")
for n in nums:
print(n)
i = 0
while i < 3:
print(i)
i += 1
6. 列表推导式(超实用)
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
阶段二:函数与模块系统
二、学习内容 & 示例
1. 定义函数
def greet(name):
print(f"Hello, {name}!")
greet("Tom")
2. 函数返回值
def add(a, b):
return a + b
result = add(3, 4)
print(result)
3. 默认参数 & 命名参数
def greet(name="World"):
print(f"Hello, {name}!")
greet() # Hello, World
greet("Alice") # Hello, Alice
4. 可变参数(*args, **kwargs)
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3)) # 6
def show_info(**kwargs):
for k, v in kwargs.items():
print(f"{k}: {v}")
show_info(name="Tom", age=22)
5. 模块导入与拆分
a.py
def square(x):
return x * x
main.py
import a
print(a.square(5)) # 25
也可以:
from a import square
print(square(5))
阶段三:面向对象编程(OOP)
一、目标
理解 Python 中类的定义与对象创建
掌握构造函数、实例方法、类变量
理解封装、继承、魔法方法(Magic Methods)
学会使用类组织代码结构,提升可复用性与可维护性
二、学习内容 & 示例
1. 定义类与对象
class Person:
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
def greet(self):
print(f"Hi, I'm {self.name} and I'm {self.age} years old.")
p = Person("Alice", 30)
p.greet()
2. 类变量 vs 实例变量
class Dog:
species = "Canine" # 类变量,所有实例共享
def __init__(self, name):
self.name = name # 实例变量,独立
d1 = Dog("Max")
d2 = Dog("Buddy")
print(d1.species) # Canine
print(d2.name) # Buddy
3. 继承
class Animal:
def speak(self):
print("Animal sound")
class Cat(Animal):
def speak(self):
print("Meow")
c = Cat()
c.speak() # Meow
4. 魔法方法(Magic Methods)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1 + p2) # Point(4, 6)
阶段四:异常处理、文件操作与模块打包
一、目标
学会使用 try/except 捕获异常,避免程序崩溃
掌握文件的读写操作(文本 / JSON)
理解模块的组织方式,并能打包为简单库
二、学习内容 & 示例
1. 异常处理 try / except
try:
result = 10 / 0
except ZeroDivisionError:
print("除数不能为0")
else:
print("没有异常")
finally:
print("无论如何都会执行")
你可以捕获特定异常,也可以捕获所有异常:
try:
int("abc")
except Exception as e:
print(f"出错了:{e}")
2. 文件操作
读取文本文件
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
写入文本文件
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, Python!")
读写 JSON 文件
import json
data = {"name": "Alice", "age": 25}
# 写入
with open("user.json", "w") as f:
json.dump(data, f)
# 读取
with open("user.json", "r") as f:
loaded = json.load(f)
print(loaded["name"])
3. 模块打包和导入结构
你可以把多个 .py 文件组织为一个模块包:
my_lib/
├── __init__.py
├── math_utils.py
└── string_utils.py
math_utils.py
def add(a, b):
return a + b
init.py
from .math_utils import add
使用:
from my_lib import add
print(add(3, 4)) # 7
阶段五:函数式编程、生成器、装饰器、迭代协议
一、目标
掌握 Python 的函数式工具(如 map / filter / lambda / zip / enumerate)
理解生成器和 yield,写出高性能懒加载逻辑
理解并编写装饰器,增强函数功能
理解迭代器与自定义迭代协议(__iter__ / next)
二、学习内容 & 示例
1. 匿名函数 lambda
add = lambda x, y: x + y
print(add(3, 4)) # 7
常配合 map()、filter() 使用:
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums)) # [1, 4, 9, 16]
even = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]
2. 生成器 & yield
def countdown(n):
while n > 0:
yield n
n -= 1
for i in countdown(3):
print(i) # 3, 2, 1
生成器是“惰性”的,适合处理大文件、大数据流。
3. 装饰器 decorator
def logger(func):
def wrapper(*args, **kwargs):
print(f"调用函数:{func.__name__}")
return func(*args, **kwargs)
return wrapper
@logger
def say_hi(name):
print(f"Hi, {name}!")
say_hi("Tom")
装饰器本质是“函数包函数”,可以为函数添加日志、缓存、权限等功能。
4. 迭代器协议:__iter__ / next
class Count:
def __init__(self, max_val):
self.i = 0
self.max = max_val
def __iter__(self):
return self
def __next__(self):
if self.i < self.max:
self.i += 1
return self.i
else:
raise StopIteration
c = Count(3)
for x in c:
print(x) # 1, 2, 3
一、什么是迭代器协议?
Python 中一个对象要成为“可迭代的”,它必须遵循迭代器协议,即实现以下两个方法:
iter():返回一个迭代器对象
next():返回下一个值,如果没有值了就抛出 StopIteration 异常
你可以这样理解:
可迭代对象:实现了 iter() 的对象
迭代器对象:实现了 iter() 和 next() 的对象
二、示例:自己实现一个迭代器类
自定义类:MyRange(start, end)
模仿 range
class MyRange:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self # 迭代器协议要求返回自身
def __next__(self):
if self.current < self.end:
val = self.current
self.current += 1
return val
else:
raise StopIteration
使用它:
for i in MyRange(1, 4):
print(i) # 输出:1, 2, 3
三、为什么需要迭代器协议?
你熟悉的这些语法,其实底层都靠它:
for x in iterable: # 本质上是:
it = iter(iterable) # 调用 iterable.__iter__()
while True:
try:
x = next(it) # 调用 it.__next__()
except StopIteration:
break
所以:
for 循环可以作用于任何实现了 iter 的对象
next() 只能作用于迭代器(带 next 方法)
四、生成器与迭代器的关系
生成器函数其实自动帮你实现了迭代器协议:
def my_gen():
yield 1
yield 2
g = my_gen()
print(next(g)) # 1
print(next(g)) # 2
这个 g 本质上就是一个迭代器(带有 iter 和 next)
五、如何判断对象是否可迭代或是迭代器?
from collections.abc import Iterable, Iterator
isinstance([1, 2, 3], Iterable) # True
isinstance([1, 2, 3], Iterator) # False
isinstance(iter([1, 2, 3]), Iterator) # True
六、实用场景
创建你自己的类并希望它能被 for in 遍历(如分页器、任务流)
惰性加载大数据(避免一次性加载占用内存)
组合生成器、流式处理数据、协程通信
好的!下面我来系统地为你讲解 Python 的协程与异步编程(asyncio),从 JS 开发者的角度出发,你会发现它跟 JS 的 async/await 机制非常类似,但又有 Python 的独特特性。
异步编程
一、什么是异步编程(async programming)?
传统函数是同步执行的:一个函数没跑完,后面的就得等。
异步编程是:函数遇到耗时操作时可以“挂起”,把执行权让给别人用,等结果到了再回来继续。
适用于:
网络请求(爬虫、API)
文件/数据库 IO
高并发任务调度
二、Python 中的 async/await 基础语法
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(say_hello())
解释:
async def 定义协程函数
await 等待一个可挂起操作(必须是“awaitable”的对象)
asyncio.run() 是入口(等价于 JS 中的 main().then())
三、多个协程并发运行
import asyncio
async def task(name, delay):
print(f"开始任务:{name}")
await asyncio.sleep(delay)
print(f"完成任务:{name}")
async def main():
await asyncio.gather(
task("A", 2),
task("B", 1),
task("C", 3)
)
asyncio.run(main())
输出顺序说明了:协程是并发执行的!
四、异步与同步的对比
五、创建自己的 awaitable 对象
只要实现了 await 方法的对象,就能被 await:
class AwaitMe:
def __await__(self):
yield from asyncio.sleep(1).__await__()
return "Done"
async def main():
result = await AwaitMe()
print(result)
asyncio.run(main())
六、异步常用 API
七、异步 IO 实战案例:批量请求网页标题
import asyncio
import aiohttp
async def fetch_title(session, url):
async with session.get(url) as resp:
text = await resp.text()
print(f"Fetched {url}: {len(text)} 字符")
async def main():
urls = [
"https://www.example.com",
"https://www.python.org",
"https://www.github.com"
]
async with aiohttp.ClientSession() as session:
tasks = [fetch_title(session, url) for url in urls]
await asyncio.gather(*tasks)
asyncio.run(main())
aiohttp 是 requests 的异步版,适合协程使用。
八、协程 vs 线程 vs 进程
九、使用场景总结
适合用异步的:
抓取网页、调用外部API
数据库批量读取
消息队列、聊天服务、任务分发系统
不适合用异步的:
纯计算密集(建议用 multiprocessing 或 C 扩展)
十、如果你要深入:
学习 aiohttp 做异步爬虫 / API
了解 asyncio.Queue, Lock, Event 等通信与控制机制
用 FastAPI 构建高并发 Web 服务(完美结合 async)
你想试试哪一个?或者我直接给你安排一个练习任务也行。