**定义:**装饰器是接收被装饰对象并返回替代对象的可调用对象。@decorator 大致等价于 func = decorator(func);装饰发生在定义阶段,而包装函数的执行发生在调用阶段。
pythonimport functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
print(f"{func.__name__}: {time.perf_counter() - start:.4f}s")
return wrapper
@timer
def add(a: int, b: int) -> int:
return a + b
assert add(2, 3) == 5
要点:functools.wraps 保留名称、文档及 __wrapped__ 等元信息;装饰器可以有参数、可以叠加;异步函数需要异步包装器,不能直接把协程对象当同步结果计时。
pythonfrom functools import wraps
def require_role(role: str):
def decorator(func):
@wraps(func)
def wrapper(user, *args, **kwargs):
if role not in user.get("roles", []):
raise PermissionError(role)
return func(user, *args, **kwargs)
return wrapper
return decorator
**面试问题:**多个装饰器的应用顺序?@A @B def f 等价于 f = A(B(f))。
可迭代对象提供 __iter__;迭代器提供 __next__ 并通常返回自身作为迭代器;next() 在结束时抛出 StopIteration。
pythonclass CountDown:
def __init__(self, n): self.n = n
def __iter__(self): return self
def __next__(self):
if self.n <= 0:
raise StopIteration
self.n -= 1
return self.n
assert list(CountDown(3)) == [2, 1, 0]
生成器函数含 yield,调用时返回生成器对象,执行可暂停/恢复。适合流式读取大文件、惰性计算和管道处理。
pythondef read_lines(path: str):
with open(path, encoding="utf-8") as file:
for line in file:
yield line.rstrip("\n")
**注意:**生成器不一定比列表更快;它主要降低峰值内存并支持流式处理。yield from 可委托子迭代器;send() 可向暂停的生成器传值。
with 调用 __enter__,退出时调用 __exit__(exc_type, exc, tb)。__exit__ 返回真值会抑制异常,因此应谨慎。
pythonfrom contextlib import contextmanager
@contextmanager
def managed_resource():
print("acquire")
try:
yield "resource"
finally:
print("release")
with managed_resource() as resource:
print(resource)
面试延伸:contextlib.asynccontextmanager、async with、数据库事务管理。
闭包是函数及其捕获的外围作用域变量绑定。可用于状态封装、装饰器和工厂函数。
pythondef counter():
n = 0
def increment():
nonlocal n
n += 1
return n
return increment
next_value = counter()
assert (next_value(), next_value()) == (1, 2)
陷阱:循环变量晚绑定;使用默认参数或工厂函数捕获每轮值。
(...)。map、filter、zip、enumerate、sorted(key=...)。itertools 用于高效迭代;functools.lru_cache 用于纯函数或可安全缓存结果。pythonfrom functools import lru_cache
@lru_cache(maxsize=128)
def fib(n: int) -> int:
if n < 2: return n
return fib(n - 1) + fib(n - 2)
assert fib(10) == 55
注意缓存的内存占用、过期策略和副作用问题。
类型注解主要用于静态分析和可读性,Python 本身不会自动强制校验函数参数类型;Pydantic 等库可实现运行时验证。
pythonfrom typing import Protocol
class Repository(Protocol):
def get(self, user_id: int) -> str | None: ...
def load_name(repo: Repository, user_id: int) -> str | None:
return repo.get(user_id)
重点:Optional[T] 与 T | None、TypedDict、TypeVar、Generic、Protocol、Callable。
描述符实现 __get__、__set__ 或 __delete__,是 property、方法绑定等机制的重要基础。理解数据描述符与非数据描述符的属性查找优先级。
pythonclass Positive:
def __set_name__(self, owner, name): self.name = name
def __get__(self, obj, owner=None):
if obj is None: return self
return obj.__dict__[self.name]
def __set__(self, obj, value):
if value <= 0: raise ValueError("must be positive")
obj.__dict__[self.name] = value
class Product:
price = Positive()
def __init__(self, price): self.price = price
wraps 作用。contextmanager 封装事务或锁。lru_cache 的缓存键、线程使用和适用条件。Protocol 与继承抽象基类的区别。**验收标准:**能从零写出装饰器、生成器、上下文管理器,并能讲清异常和资源释放语义。
备案号:豫ICP备2023003398号-1 工信部备案管理系统:豫ICP备2023003398号-1