1. 函数高级特性
闭包、装饰器、偏函数、函数式工具。闭包可查看 __closure__;装饰器含普通、带参数、类装饰器,并用 functools.wraps 保留元信息;functools.partial 固定部分参数;函数式工具包括 map/filter/reduce、lambda、operator。
python
from functools import wraps
def log(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"call {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log
def add(a, b):
return a + b
2. 迭代器与生成器
可迭代对象实现 __iter__,迭代器实现 __iter__ 和 __next__。生成器函数用 yield 惰性求值,节省内存,支持 send()、throw()、close()、yield from。itertools 提供 chain、groupby、product、permutations、islice 等。
python
def count_down(n):
while n > 0:
yield n
n -= 1
for i in count_down(3):
print(i)
```
3. 上下文管理器
with 语句自动管理资源,可实现 __enter__ 和 __exit__。contextlib.contextmanager 用生成器快速写上下文管理器,contextlib.ExitStack 动态管理多个上下文。
python
from contextlib import contextmanager
@contextmanager
def open_file(path):
f = open(path)
try:
yield f
finally:
f.close()
4. 面向对象进阶
魔术方法包括 __new__、__init__、__call__、__getattr__、__setattr__、__getitem__、__eq__、__hash__、__str__、__repr__ 等。属性管理涉及 property、__slots__、描述符协议。继承与 MRO 使用 C3 算法和 super()。抽象基类用 abc.ABC、@abstractmethod。数据类用 @dataclass。元类中 type 是元类,metaclass= 可控制类创建,ORM 常用。
python
class MyMeta(type):
def __new__(cls, name, bases, attrs):
attrs["version"] = 1
return super().__new__(cls, name, bases, attrs)
class A(metaclass=MyMeta):
pass
print(A.version) # 1
5. 元编程
动态属性用 getattr、setattr、hasattr、delattr。动态导入用 importlib.import_module。装饰器加元类可实现插件系统、注册表。exec / eval 谨慎使用。反射与内省用 inspect 模块。
6. 并发与异步
GIL 是 CPython 全局解释器锁,多线程适合 IO 密集,不适合 CPU 密集。多线程用 threading、Lock、Queue。多进程用 multiprocessing 绕过 GIL。线程/进程池用 concurrent.futures.ThreadPoolExecutor、ProcessPoolExecutor。异步 IO 用 asyncio、async/await、事件循环、Task、Future。IO 密集选线程或异步,CPU 密集选多进程,高并发网络选 asyncio + aiohttp / httpx。
python
import asyncio
async def main():
await asyncio.sleep(1)
print("done")
asyncio.run(main())
7. 内存管理与性能优化
引用计数加垃圾回收,含标记清除、分代回收。循环引用用 gc 模块、weakref 弱引用。__slots__ 减少实例内存。性能分析用 cProfile、timeit、memory_profiler。优化技巧包括多用内置函数和局部变量、用生成器代替大列表、functools.lru_cache 缓存、避免频繁全局查找。
8. 类型提示与类型检查
typing 提供 List、Dict、Optional、Union、Callable、TypeVar、Generic。高级类型有 Protocol、TypedDict、Literal、NewType。支持泛型编程。工具用 mypy、pyright。
python
from typing import TypeVar, Generic
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value
```
9. 标准库进阶
collections 提供 defaultdict、Counter、deque、namedtuple。itertools 提供组合、排列、分组、无限迭代器。functools 提供 lru_cache、partial、reduce、wraps。contextlib 提供 contextmanager、suppress、ExitStack。其他常用有 pathlib、logging、argparse、subprocess、json、pickle、sqlite3、asyncio、concurrent.futures、multiprocessing。
10. 工程化与生态
虚拟环境用 venv、pip、poetry。打包发布用 pyproject.toml、setuptools、build。测试用 pytest、unittest、mock。代码质量用 black、ruff、flake8、mypy。设计模式有单例、工厂、观察者、策略、装饰器。常用框架有 Django、Flask、FastAPI、SQLAlchemy、Pandas、NumPy。




