1. 函数的高级特性
a. 装饰器 (Decorators)
装饰器是一种强大的工具,允许你在不修改原函数代码的情况下,为其增加新的功能。它本质上是一个返回函数的高阶函数。
应用场景: 日志记录、性能测试(计算运行时间)、权限校验、事务处理、缓存等。
示例:计算函数运行时间
python
import time
from functools import wraps
def timer(func):
@wraps(func) # 保留原函数的元信息
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
print(f"{func.__name__} 执行耗时: {end_time - start_time:.4f} 秒")
return result
return wrapper
@timer # 相当于 `slow_function = timer(slow_function)`
def slow_function():
time.sleep(2)
return "Done"
result = slow_function()
# 输出: slow_function 执行耗时: 2.0023 秒
b. 闭包 (Closures)
闭包是指引用了外部函数作用域中变量的内部函数。即使外部函数已经执行完毕,内部函数仍然可以记住并访问那些变量。
示例:
python
def make_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 输出: 10
print(triple(5)) # 输出: 15
# 内部函数 multiplier 记住了外部传入的 factor
c. 匿名函数与 Lambda
lambda
关键字用于创建小巧的匿名函数,通常用于需要函数对象作为参数的场合。
示例:与 sorted
, filter
, map
等结合使用
python
# 按字符串长度排序
words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words) # 输出: ['date', 'apple', 'banana', 'cherry']
# 过滤偶数
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # 输出: [2, 4, 6]
2. 面向对象编程 (OOP) 高级特性
a. 魔术方法 (Magic/Dunder Methods)
以双下划线 __
开头和结尾的方法,用于实现类的特殊行为(如运算符重载、容器行为等)。
__init__
: 构造函数__str__
,__repr__
: 定义对象的字符串表示形式__len__
: 定义len()
行为__getitem__
,__setitem__
: 实现索引操作,让实例像列表/字典一样__iter__
和__next__
: 让对象可迭代__enter__
和__exit__
: 实现上下文管理器(用于with
语句)
示例:创建一个自定义的列表类
python
class MyList:
def __init__(self, *args):
self.data = list(args)
def __getitem__(self, index):
return self.data[index]
def __setitem__(self, index, value):
self.data[index] = value
def __len__(self):
return len(self.data)
def __repr__(self):
return f"MyList({self.data})"
my_list = MyList(1, 2, 3)
print(my_list[1]) # 输出: 2 (调用 __getitem__)
my_list[1] = 20 # (调用 __setitem__)
print(len(my_list)) # 输出: 3 (调用 __len__)
print(my_list) # 输出: MyList([1, 20, 3]) (调用 __repr__)
b. 元类 (Metaclasses)
元类是类的类,用于创建类。它是 OOP 的最高级概念,可以控制类的创建行为。绝大多数情况下不需要使用,但在需要深度定制类创建过程(如 ORM框架、API 设计)时非常强大。
示例:使用 type
动态创建类
python
# 传统方式
class MyClass:
x = 10
# 等价于以下元类方式
def my_method(self):
return self.x
MyClass = type('MyClass', (object,), {'x': 10, 'my_method': my_method})
c. 描述符 (Descriptors)
描述符是实现了 __get__
, __set__
, 或 __delete__
方法的对象。它用于管理另一个类的属性访问,是实现 @property
, @staticmethod
, @classmethod
的基础。
示例:实现一个简单的类型检查描述符
python
class Typed:
def __init__(self, type_):
self.type = type_
def __set_name__(self, owner, name):
self.name = name
def __set__(self, instance, value):
if not isinstance(value, self.type):
raise TypeError(f"Expected {self.type}")
instance.__dict__[self.name] = value
class Person:
name = Typed(str)
age = Typed(int)
p = Person()
p.name = "Alice" # OK
p.age = "30" # TypeError: Expected <class 'int'>
3. 元编程 (Metaprogramming)
a. 生成器 (Generators) 和 yield
生成器是一种特殊的迭代器,它使用 yield
关键字逐步产生值,而不是一次性返回所有值。这可以极大地节省内存,尤其是在处理大型数据集或流时。
示例:读取大文件
python
def read_large_file(file_path):
with open(file_path, 'r') as f:
for line in f:
yield line.strip()
# 逐行处理,不会一次性将整个文件加载到内存中
for line in read_large_file('huge_log.txt'):
process_line(line)
b. 上下文管理器 (Context Managers) 与 with
语句
用于管理资源(如文件、锁、网络连接),确保它们被正确初始化和清理。除了使用 with
,还可以用 contextlib
模块创建。
示例:使用 contextlib
创建上下文管理器
python
from contextlib import contextmanager
@contextmanager
def managed_resource(*args):
# 相当于 __enter__: 分配资源
resource = acquire_resource(*args)
try:
yield resource
finally:
# 相当于 __exit__: 释放资源
release_resource(resource)
# 使用
with managed_resource('arg1', 'arg2') as r:
do_something(r) # r 就是 yield 出来的 resource
4. 并发与并行
a. 协程与异步编程 (asyncio
)
用于编写单线程高并发代码,特别适合 I/O 密集型任务(如网络请求、文件读写)。
示例:异步获取多个网页
python
import asyncio
import aiohttp
async def fetch_url(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = ['http://example.com', 'http://example.org']
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)
for result in results:
print(result[:100]) # 打印每个结果的前100个字符
asyncio.run(main())
b. 多进程 (multiprocessing
)
利用多核 CPU 执行真正的并行计算,适合 CPU 密集型任务。它避开了 GIL(全局解释器锁)的限制。
示例:并行计算
python
from multiprocessing import Pool
def cpu_intensive_task(n):
return n * n
if __name__ == '__main__':
with Pool(processes=4) as pool: # 创建4个进程的池
numbers = [1, 2, 3, 4, 5]
# 将任务映射到多个进程并行执行
results = pool.map(cpu_intensive_task, numbers)
print(results) # 输出: [1, 4, 9, 16, 25]
5. 模块与包的高级用法
a. 动态导入
python
module_name = "os"
imported_module = __import__(module_name)
print(imported_module.getcwd())
b. 导入钩子 (Import Hooks)
通过 importlib
和 sys.meta_path
可以自定义导入器的行为,极其高级。
6. 性能分析与优化
a. 使用 cProfile
进行性能分析
找出代码的性能瓶颈。
bash
python -m cProfile -s time my_script.py
b. 使用 C 扩展
- Cython: 将 Python 代码编译成 C 扩展模块,大幅提升性能。
- ctypes / CFFI: 直接调用 C 语言的共享库。
c. 使用高效的数据结构
collections
模块:deque
(双端队列),Counter
(计数器),defaultdict
(带默认值的字典),namedtuple
(命名元组)。array
模块:紧凑型数组,用于存储大量同质数据。
学习路径建议
- 先巩固基础:确保对 Python 基础语法、数据结构、函数、类有扎实的理解。
- 逐个击破 :不要试图一次性掌握所有高级特性。先从最实用的开始,如装饰器、生成器、上下文管理器。
- 在实践中学习:找一个实际项目,尝试应用这些高级特性。例如,用装饰器实现日志功能,用生成器处理大数据文件。
- 阅读优秀代码:阅读 Django、Flask、Requests 等知名开源项目的源码,是学习高级用法的最佳途径之一。
- 按需深入 :遇到特定场景时再去深入研究对应的技术,如需要高性能计算时研究 Cython,需要高并发时研究
asyncio
。
掌握这些高级用法将使你从一个 Python 使用者转变为一个真正的 Python 开发者。