🌟 Python为何如此受欢迎?
print("人生苦短,我用Python!") # 简洁优雅的语法
print("从网站开发到人工智能,无所不能!") # 强大的功能
print("全球数百万开发者共同维护的生态圈") # 活跃的社区
第一章:基石 · 语法内核与变量底层 📌
1.1 变量赋值与内存机制(不仅是“盒子”)
1.2 运算符精讲
第二章:数据结构 · 方法签名全展开 📚
2.1 字符串(str)—— 全方法分类
2.2 列表(list)—— 作为栈与队列
💡 切片赋值:lst[1:3] = [10, 20](替换元素,长度可变)
💡 列表乘法:[[]] * 3 大坑!会复制引用,导致内层列表联动。应使用列表推导 [[] for _ in range(3)]。
2.3 字典(dict)—— 哈希表深度
# 字典推导 + 计数 (◕‿◕)
text = "abracadabra"
char_count = {char: text.count(char) for char in set(text)}
# 更高效用 collections.Counter
2.4 集合(set)与不可变集合(frozenset)
第三章:控制流 · 高级模式匹配(match-case) 🔀
Python 3.10 引入的 结构模式匹配(别当成简单的 switch!)
# 匹配字面量、变量、结构 (ノ◕ヮ◕)ノ
def process(command):
match command.split():
case ["quit"]:
print("退出")
case ["move", x, y] if int(x) > 0: # 守卫(Guard)
print(f"正向移动 {x}, {y}")
case ["move", x, y]:
print(f"移动 {x}, {y}")
case [action, *rest]: # 解包剩余部分
print(f"未知动作: {action}, 参数: {rest}")
case _: # 通配符
print("无效命令")
# 匹配类实例
class Point:
__match_args__ = ("x", "y")
def __init__(self, x, y): self.x = x; self.y = y
def where_is(point):
match point:
case Point(0, 0): print("原点")
case Point(x, 0): print(f"X轴 {x}")
case Point(0, y): print(f"Y轴 {y}")
case Point(x, y) if x == y: print(f"对角线 {x}")
case _: print("其他位置")
第四章:函数 · 从签名到装饰器工厂 🛠️
4.1 参数种类(必填、默认、可变、关键字独占)
# 组合大法 (。◕‿◕。)
def complex_func(a, b, /, c, d, *args, e, f=10, **kwargs):
# a, b 必须位置;c, d 位置或关键字;args 可变位置;e 必须关键字;f 默认关键字;kwargs 可变关键字
pass
4.2 闭包与 nonlocal / global
def outer():
count = 0
def inner():
nonlocal count # 必须声明,否则视为局部变量
count += 1
return count
return inner
counter = outer()
print(counter()) # 1
print(counter()) # 2
4.3 装饰器(带参数与类装饰器)
import functools
import time
# 带参数的装饰器 ( ̄▽ ̄)ノ
def retry(max_attempts=3, delay=1):
def decorator(func):
@functools.wraps(func) # 保留原函数元数据!
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"第 {attempt} 次失败: {e}")
time.sleep(delay)
return None
return wrapper
return decorator
@retry(max_attempts=5, delay=0.5)
def unstable_network_call():
import random
if random.random() < 0.7:
raise ConnectionError("模拟失败")
return "成功 🎉"
4.4 高阶函数:functools 精华
第五章:迭代器 · 生成器 · 协程(yield 三部曲)🌀
# 无限序列生成器 (`・ω・´)
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
[next(fib) for _ in range(10)] # [0,1,1,2,3,5,8,13,21,34]
# yield from 扁平化嵌套
def flatten(nested):
for sub in nested:
yield from sub # 递归展开
print(list(flatten([[1,2], [3, [4,5]]]))) # 注意:只展一层,需递归处理多层级
第六章:内置函数 · 全分类大辞典(按功能分组)🗂️
6.1 数学与数值
6.2 序列与迭代
6.3 对象与属性(反射)
6.4 编译与执行(安全警告⚠️)
6.5 类型转换
第七章:类与对象 · 元编程浅探 🏛️
7.1 魔法方法(双下划线)速查表
# 单例模式与 __new__ (。♥‿♥。)
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
# 上下文管理器手动实现
class ManagedFile:
def __init__(self, name, mode):
self.name = name; self.mode = mode
def __enter__(self):
self.file = open(self.name, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
if exc_type:
print(f"异常被捕获: {exc_val}")
return True # 吞掉异常(慎用)
7.2 数据类(@dataclass)vs 传统类
from dataclasses import dataclass, field
from typing import List
@dataclass(order=True) # 支持排序
class InventoryItem:
name: str
price: float = field(repr=True, compare=True)
quantity: int = field(default=0, compare=False)
tags: List[str] = field(default_factory=list) # 避免可变默认值!
def total_cost(self) -> float:
return self.price * self.quantity
# 自动生成 __init__, __repr__, __eq__, __hash__ 等
第八章:异常 · 层级与自定义(最佳实践)🚨
8.1 内建异常层级(简略)
BaseException
├── SystemExit, KeyboardInterrupt (应捕获 Exception 而非 BaseException)
├── Exception
│ ├── ArithmeticError (ZeroDivisionError, OverflowError)
│ ├── LookupError (IndexError, KeyError)
│ ├── TypeError, ValueError, AttributeError
│ └── OSError (FileNotFoundError, PermissionError)
8.2 自定义异常与 raise from
class CustomAPIError(Exception):
"""自定义 API 错误基类"""
def __init__(self, message, status_code=None):
super().__init__(message)
self.status_code = status_code
try:
raise ConnectionError("连接超时")
except ConnectionError as e:
# 链式异常,保留原始上下文 (╯°□°)╯
raise CustomAPIError("请求失败") from e
✨ finally 中 return 会吞掉异常(极不推荐!)
第九章:文件与 I/O · 所有模式详解 📁
# 使用 seek 和 tell 操作指针 (`・ω・´)
with open('data.bin', 'rb+') as f:
f.write(b'\x00\x01\x02')
f.seek(1) # 移动到索引1
data = f.read(1) # b'\x01'
print(f.tell()) # 当前指针位置 -> 2
上下文管理器进阶:同时打开多个文件
from contextlib import ExitStack
with ExitStack() as stack:
files = [stack.enter_context(open(f'file_{i}.txt', 'w')) for i in range(3)]
for f in files:
f.write("批量管理 ✨")
第十章:类型提示(Type Hints)与 typing 深度 🧬
from typing import Protocol, runtime_checkable
# 鸭子类型 + 静态检查 (。◕‿◕。)
@runtime_checkable
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable):
obj.draw()
# 只要实现了 draw 方法的类,即使不继承,也能通过类型检查
第十一章:并发编程速览(多线程 / 异步)⚡
import asyncio
async def fetch_data(delay, name):
print(f"开始 {name} (`・ω・´)")
await asyncio.sleep(delay) # 模拟IO
print(f"完成 {name}")
return f"结果 {name}"
async def main():
# 并发执行
results = await asyncio.gather(
fetch_data(2, "A"),
fetch_data(1, "B"),
fetch_data(3, "C")
)
print(results) # ['结果 A', '结果 B', '结果 C']
# asyncio.run(main())
第十二章:性能优化与调试技巧 🚀
12.1 性能测试
import timeit
# 测试列表推导 vs 循环
print(timeit.timeit('[x**2 for x in range(1000)]', number=10000))
print(timeit.timeit('for i in range(1000): lst.append(i**2)', setup='lst=[]', number=10000))
12.2 __slots__ 节省内存
class WithoutSlots:
def __init__(self, name, age): self.name=name; self.age=age
class WithSlots:
__slots__ = ('name', 'age') # 禁止动态添加属性,大幅减少内存使用
def __init__(self, name, age): self.name=name; self.age=age
12.3 字符串拼接(join 优于 +=)
# ❌ 慢:每次 += 创建新对象
s = ""
for i in range(1000):
s += str(i)
# ✅ 快
''.join(map(str, range(1000)))
12.4 调试工具
🔥 终章:3.10 ~ 3.12 新特性彩蛋
🚀 Python学习路线图
-
基础语法 → 2. 数据结构 → 3. 函数编程
-
面向对象 → 5. 常用模块 → 6. 项目实践
# 你的第一个Python程序
print("✨ 恭喜完成Python入门! ✨")
print("接下来探索: ")
print(" - 网页开发(Django/Flask)")
print(" - 数据分析(Pandas/Matplotlib)")
print(" - 人工智能(TensorFlow/PyTorch)")
print(" - 自动化脚本/爬虫")
💪 编程就像搭积木,每天进步一点点!
🐢 坚持练习比天赋更重要,动手写代码吧!
🎉 欢迎加入Python开发者的大家庭!
点我前往Python官网
暂无评论内容