| 特性 | 核心关键词 | 适用场景 | 收益 |
|---|---|---|---|
| 装饰器 | @, wraps |
日志、鉴权、缓存 | 代码复用,逻辑分离 |
| 生成器 | yield |
大数据流处理 | 极省内存,惰性计算 |
| 上下文管理 | with |
文件、锁、DB连接 | 资源安全,自动清理 |
| 魔法方法 | __len__, __call__ |
自定义数据类型 | 让对象更符合直觉 |
| Asyncio | async/await |
高并发 Web/爬虫 | 高吞吐量,非阻塞 IO |
Python 支持很多函数式编程的概念,其中最核心的是装饰器和匿名函数。
装饰器是 Python 中最强大的特性之一。它允许你在不修改原函数代码的情况下,动态地增加功能(如日志、计时、权限校验)。
核心原理: 闭包(Closure)和函数作为一等公民(First-class citizen)。
语法: 使用 @ 符号。
Python
import time
from functools import wraps
def timer(func):
@wraps(func) # 保留原函数的元数据(如函数名、文档字符串)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} 执行耗时: {end - start:.4f} 秒")
return result
return wrapper
@timer
def laborious_task(n):
return sum(range(n))
laborious_task(1000000)
虽然 lambda 只是简单的单行匿名函数,但配合 map, filter, reduce 使用时非常高效。
Python 对数据的处理方式极其灵活,核心在于惰性求值 (Lazy Evaluation)。
yield生成器是一种特殊的迭代器。与列表一次性把所有数据加载到内存不同,生成器用一个生成一个,极大地节省内存。
Python
# 列表推导式(内存占用大)
my_list = [x * x for x in range(1000000)]
# 生成器表达式(内存占用极小)
my_gen = (x * x for x in range(1000000))
# 使用 yield 定义生成器函数
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for val in fibonacci(5):
print(val)
使用 with 语句来自动管理资源(如文件打开/关闭、数据库连接、锁)。
contextlib 库或实现 __enter__ 和 __exit__ 魔法方法。Python
class FileManager:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'w')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
# 自动关闭文件,即使发生异常
with FileManager('test.txt') as f:
f.write('Hello World')
Python 的类机制非常动态,你可以深入底层控制类的创建和行为。
以双下划线开头和结尾的方法(如 __init__)。通过实现这些方法,你可以让自定义对象表现得像内置类型一样(运算符重载)。
__str__ / __repr__: 控制对象的字符串显示。
__getitem__ / __setitem__: 让对象像列表或字典一样支持索引访问。
__call__: 让对象实例像函数一样被调用。
这是 Python 中最晦涩但也最强大的特性之一。类是创建对象的模板,而元类是创建类的模板。 它可以用来拦截类的创建过程,自动修改类属性或进行注册。
Python
# 简单的元类示例:强制所有类属性大写
class UpperAttrMeta(type):
def __new__(cls, clsname, bases, dct):
new_attrs = {}
for name, value in dct.items():
if not name.startswith('__'):
new_attrs[name.upper()] = value
else:
new_attrs[name] = value
return super().__new__(cls, clsname, bases, new_attrs)
class MyClass(metaclass=UpperAttrMeta):
bar = 'bip'
print(hasattr(MyClass, 'bar')) # False
print(hasattr(MyClass, 'BAR')) # True
__slots__如果你需要创建成千上万个小对象,使用 __slots__ 可以告诉 Python 不要为每个实例创建 __dict__,从而节省大量内存并提高属性访问速度。
随着 Python 3.5+ 引入 async 和 await,Python 在高并发 IO 密集型任务(如网络爬虫、Web 服务)上表现优异。
这是 Python 原生的异步编程库,基于事件循环 (Event Loop)。它允许你在单线程中并发处理多个任务。
Python
import asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
# 并发运行两个任务
await asyncio.gather(
say_after(1, 'hello'),
say_after(2, 'world')
)
# asyncio.run(main())
多线程 (threading): 受限于 GIL (全局解释器锁),Python 的多线程不能利用多核 CPU 进行并行计算,只适合 IO 密集型任务。
多进程 (multiprocessing): 绕过 GIL,每个进程有独立的 Python 解释器,适合 CPU 密集型计算。
© 2026 myfk. All rights reserved.