"高级用法" 并不是指某个特定的语法,而是一种编程思想、编程范式和工具使用的综合体现,它意味着你不再仅仅把 Python 当作一个简单的脚本语言,而是能够利用其强大的特性来编写更高效、更健壮、更可维护、更具扩展性的代码。

下面我将从几个核心方面,结合代码示例,来系统地讲解 Python 的高级用法。
目录
- 面向对象编程的精髓
- 魔法方法 (
__init__,__str__,__len__等) - 描述符
- 元类
- 魔法方法 (
- 函数式编程思想
lambda表达式map(),filter(),reduce()- 装饰器
- 生成器 与
yield - 上下文管理器 与
with语句
- 并发与异步编程
- 多线程
- 多进程
asyncio异步 I/O
- 元编程与动态特性
- 动态属性访问 (
__getattr__,__setattr__) - 动态方法调用
- 动态创建类
- 动态属性访问 (
- 现代 Python 工具链
- 类型提示
- 数据类
- 类型检查工具
- 性能优化
- 性能分析工具
- JIT 编译 (PyPy)
- 关键部分使用 C/C++ 扩展 (Cython)
面向对象编程的精髓
Python 的 OOP 支持非常灵活,远超 class 和 self 的基本用法。
a. 魔法方法
魔法方法是 Python 类中以双下划线 __ 开头和结尾的特殊方法,它们可以让你自定义类的行为,使其能像内置类型一样工作。
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
# 定义对象的字符串表示形式
def __str__(self):
return f"'{self.title}' by {self.author}"
# 定义对象的官方、详细字符串表示形式 (用于调试)
def __repr__(self):
return f"Book(title='{self.title}', author='{self.author}', pages={self.pages})"
# 定义 len() 函数的行为
def __len__(self):
return self.pages
# 定义 + 运算符的行为
def __add__(self, other):
if isinstance(other, Book):
return Book(
f"{self.title} & {other.title}",
f"{self.author} & {other.author}",
self.pages + other.pages
)
return NotImplemented
# 使用
book1 = Book("Python高级编程", "Gaojiyongfa", 300)
book2 = Book("流畅的Python", "Luciano Ramalho", 500)
print(book1) # 调用 __str__
print(repr(book1)) # 调用 __repr__
print(f"这本书有 {len(book1)} 页。") # 调用 __len__
book3 = book1 + book2 # 调用 __add__
print(book3)
b. 描述符
描述符是一种强大的协议,它允许你创建一个属性,其行为由另一个类来控制,这是实现 ORM(如 SQLAlchemy)、属性验证、计算属性等的核心。

class ValidatedAttribute:
def __init__(self, name=None, validator=None):
self.name = name
self.validator = validator
def __set_name__(self, owner, name):
self.name = '_' + name
def __get__(self, instance, owner):
if instance is None:
return self
return getattr(instance, self.name)
def __set__(self, instance, value):
if self.validator:
value = self.validator(value)
setattr(instance, self.name, value)
def positive_integer(value):
if not isinstance(value, int) or value <= 0:
raise ValueError("必须是正整数")
return value
class User:
age = ValidatedAttribute(validator=positive_integer)
score = ValidatedAttribute(validator=positive_integer)
# 使用
user = User()
user.age = 25
print(user.age) # 25
try:
user.age = -5
except ValueError as e:
print(e) # 必须是正整数
try:
user.score = "abc"
except ValueError as e:
print(e) # 必须是正整数
c. 元类
元类是“类的类”,它定义了类是如何被创建的,是 Python 中最底层的、最强大的工具之一,通常用于框架和库的底层设计,Django ORM。
# 一个简单的元类,用于在创建类时自动添加一个属性
class AddMetaAttr(type):
def __new__(cls, name, bases, dct):
print(f"正在创建类 {name}")
dct['created_by'] = '元类 AddMetaAttr'
return super().__new__(cls, name, bases, dct)
# 使用元类创建类
class MyClass(metaclass=AddMetaAttr):
pass
print(MyClass.created_by) # 输出: 元类 AddMetaAttr
函数式编程思想
函数式编程将计算视为数学函数的求值,避免使用状态变化和可变数据。
a. lambda 表达式
用于创建匿名函数,常与 map, filter, sorted 等函数结合使用。
# 传统函数
def square(x):
return x * x
# lambda 表达式
square_lambda = lambda x: x * x
print(square_lambda(5)) # 25
# 与 sorted 结合使用
points = [(1, 5), (2, 3), (4, 1)]
# 按照元组的第二个元素排序
sorted_points = sorted(points, key=lambda p: p[1])
print(sorted_points) # [(4, 1), (2, 3), (1, 5)]
b. map(), filter(), reduce()
map(function, iterable): 对可迭代对象中的每个元素应用函数。filter(function, iterable): 过滤可迭代对象,保留使函数返回True的元素。reduce(function, iterable): 将可迭代对象中的元素依次通过函数进行累积计算(需从functools导入)。
from functools import reduce numbers = [1, 2, 3, 4, 5] # map: 计算平方 squared = list(map(lambda x: x**2, numbers)) print(squared) # [1, 4, 9, 16, 25] # filter: 过滤出偶数 evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4] # reduce: 计算所有数字的乘积 product = reduce(lambda x, y: x * y, numbers) print(product) # 120
c. 装饰器
装饰器是一个接受函数作为参数并返回一个新函数的“包装器”,它在不修改原函数代码的情况下,增加新功能。

import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"函数 {func.__name__} 执行耗时: {end_time - start_time:.4f} 秒")
return result
return wrapper
@timer_decorator
def slow_function(n):
time.sleep(n)
return "Done"
print(slow_function(2))
# 输出:
# 函数 slow_function 执行耗时: 2.0012 秒
# Done
d. 生成器 与 yield
生成器是一种特殊的迭代器,使用 yield 关键字而不是 return,它在每次 yield 后暂停函数状态,并在下次被调用时从暂停处继续执行,这极大地节省了内存,因为它不会一次性生成所有值。
# 生成斐波那契数列
def fibonacci_generator(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
# 使用生成器
fib_gen = fibonacci_generator(10)
for number in fib_gen:
print(number, end=" ") # 0 1 1 2 3 5 8 13 21 34
# 对比:返回列表的函数会占用更多内存
def fibonacci_list(n):
result = []
a, b = 0, 1
for _ in range(n):
result.append(a)
a, b = b, a + b
return result
e. 上下文管理器 与 with 语句
with 语句用于确保资源(如文件、网络连接)在使用后被正确释放,即使发生错误,通过实现 __enter__ 和 __exit__ 方法,任何对象都可以成为上下文管理器。
# 自定义上下文管理器
class ManagedFile:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
print("打开文件...")
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
print("关闭文件...")
self.file.close()
# 如果返回 True,则会抑制异常
return False
# 使用
with ManagedFile('my_file.txt', 'w') as f:
f.write("Hello, Advanced Python!")
# 退出 with 块时,__exit__ 会被自动调用,文件被关闭
并发与异步编程
对于 I/O 密集型任务(如网络请求、文件读写),并发是提升性能的关键。
a. 多线程 vs. 多进程
- 多线程: 适合 I/O 密集型任务,由于 Python 的 GIL(全局解释器锁),多线程不能真正并行执行 CPU 密集型任务。
- 多进程: 适合 CPU 密集型任务,每个进程有独立的 Python 解释器和内存空间,可以绕过 GIL 实现真正的并行,但开销更大。
b. asyncio 异步 I/O
asyncio 是 Python 的官方异步 I/O 框架,它使用单线程和事件循环来高效处理大量并发连接,特别适合网络服务。
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay) # 非阻塞的睡眠,让出控制权
print(what)
async def main():
print(f"开始于 {time.strftime('%X')}")
# 创建两个任务
task1 = asyncio.create_task(say_after(1, '你好'))
task2 = asyncio.create_task(say_after(2, '世界'))
await task1
await task2
print(f"结束于 {time.strftime('%X')}")
# 运行主协程
asyncio.run(main())
# 输出:
# 开始于 ... (时间戳)
# 1秒后: 你好
# 2秒后: 世界
# 结束于 ... (时间戳, 总耗时约2秒)
# 如果是同步代码,总耗时会是3秒。
元编程与动态特性
Python 的动态特性允许你在运行时修改代码结构。
class Person:
def __init__(self, name):
self.name = name
# 动态添加一个方法
def greet(self):
print(f"你好, 我是 {self.name}")
Person.greet = greet
p = Person("张三")
p.greet() # 输出: 你好, 我是 张三
# 动态添加一个类属性
Person.species = "智人"
print(p.species) # 输出: 智人
现代 Python 工具链
a. 类型提示
从 Python 3.5 开始,官方支持类型提示,它本身不会在运行时进行检查,但能极大地提高代码的可读性,并帮助静态分析工具(如 MyPy)发现潜在的错误。
from typing import List, Dict, Optional
def process_data(data: List[int]) -> Dict[str, Optional[int]]:
if not data:
return {"status": "error", "result": None}
return {
"status": "success",
"result": sum(data) / len(data)
}
# MyPy 等工具可以在这里检查类型是否匹配
b. 数据类
Python 3.7+ 引入了 @dataclass 装饰器,它能自动为类生成 __init__, __repr__, __eq__ 等方法,让代码更简洁。
from dataclasses import dataclass
@dataclass
class Product:
id: int
name: str
price: float
description: str = "无描述" # 带默认值
def get_discounted_price(self, discount: float) -> float:
return self.price * (1 - discount)
p = Product(id=1, name="笔记本电脑", price=9999.0)
print(p) # 输出: Product(id=1, name='笔记本电脑', price=9999.0, description='无描述')
性能优化
当遇到性能瓶颈时,可以采取以下策略:
- 性能分析: 使用
cProfile或line_profiler找到代码中最耗时的部分。 - 算法优化: 确保你使用了最优的算法和数据结构(用
set或dict进行成员检查比list快得多)。 - 使用 NumPy/Pandas: 对于数值计算和数据分析,使用这些库比纯 Python 循环快几个数量级。
- JIT 编译: 使用 PyPy 解释器,它可以在运行时将热点代码编译为机器码。
- Cython: 将 Python 代码编译成 C 扩展,以获得接近 C 的性能。
| 领域 | 核心概念 | 解决的问题 |
|---|---|---|
| OOP | 魔法方法, 描述符, 元类 | 增强类的行为,实现高级框架和库 |
| 函数式 | lambda, map/filter, 装饰器, 生成器, with |
编写更简洁、声明式、可维护的代码 |
| 并发 | threading, multiprocessing, asyncio |
提升程序性能,处理 I/O 或 CPU 密集型任务 |
| 元编程 | 动态属性和方法 | 在运行时灵活地创建和修改代码结构 |
| 现代工具 | 类型提示, 数据类 | 提高代码质量、可读性和开发效率 |
| 性能 | 分析, 算法, 外部库, Cython | 解决程序运行速度慢的问题 |
掌握这些高级用法,意味着你已经从“会用 Python” 进阶到了“精通 Python”,它不仅能让你写出更优雅的代码,更能让你在面对复杂问题时,有更多、更强大的解决方案,建议从装饰器、生成器和上下文管理器开始实践,它们在日常开发中应用最广泛,也最容易上手。
