9. 高级Python
9.1 迭代器与生成器
迭代器:
- 迭代器是一种遵循迭代器协议的对象,该协议要求对象实现两个特殊的方法:
__iter__()
和__next__()
。 __iter__()
方法返回迭代器自身,而__next__()
方法返回序列中的下一个值。- 当没有更多的值时,
__next__()
方法会抛出StopIteration
异常。
示例代码:
class EvenNumberIterator:
def __init__(self, numbers):
self.numbers = numbers
self.index = 0
def __iter__(self):
return self
def __next__(self):
while self.index < len(self.numbers):
current_number = self.numbers[self.index]
self.index += 1
if current_number % 2 == 0:
return current_number
raise StopIteration
# 创建一个包含数字的列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 创建一个 EvenNumberIterator 实例
even_numbers = EvenNumberIterator(numbers)
# 使用 for 循环遍历迭代器
for number in even_numbers:
print(number)
# 结果
2
4
6
8
10
生成器:
- 生成器是一种特殊的迭代器,它允许程序员简洁地编写用于遍历数据的函数。
- 生成器函数使用
yield
关键字而不是return
来返回值。yield
可以被看作是返回一个值并保存函数的状态,使得下次调用时可以从上次停止的地方继续执行。 - 生成器函数不需要显式地实现迭代器协议,它们自动支持迭代器接口。
示例代码:假设我们需要一个生成器函数来生成斐波那契数列中的前N个数
def fibonacci(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
# 指定要生成的斐波那契数的数量
n = 10
# 调用生成器函数
fib_gen = fibonacci(n)
# 使用 for 循环遍历生成器
for num in fib_gen:
print(num)
# 结果
0
1
1
2
3
5
8
13
21
34
9.2 装饰器 (decorators)
装饰器:
- 装饰器是修改其他函数行为的一种方式,通常用来添加额外的功能或者修改现有功能。
- 装饰器本质上是一个接受函数作为参数的函数,并返回一个新的函数。
- 装饰器可以用来实现诸如缓存、日志记录、性能度量等功能。
示例代码:
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before the function is called.")
result = func(*args, **kwargs)
print("After the function is called.")
return result
return wrapper
@my_decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Alice")
# 输出:
# Before the function is called.
# Hello, Alice!
# After the function is called.
9.3 上下文管理器与 `with` 语句
上下文管理器:
- 上下文管理器允许用户创建一个环境,在这个环境中某些操作可以安全地执行。
- 上下文管理器通过实现
__enter__()
和__exit__()
方法来定义上下文管理器的行为。 with
语句用于确保资源的正确清理,即使在发生异常的情况下也是如此。
示例代码:
class ManagedFile:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'r')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
with ManagedFile('example.txt') as f:
for line in f:
print(line)
# 文件在离开 with 块后会被自动关闭
9.4 异步编程基础 (asyncio)
异步编程:
- 异步编程允许程序在等待某些操作完成时执行其他任务。
- Python 的
asyncio
库提供了实现异步编程的基础设施。 - 异步编程的关键概念包括协程、事件循环、Future/Task 对象等。
示例代码:
import asyncio
async def my_coroutine():
print("Start")
await asyncio.sleep(1)
print("End")
async def main():
task = asyncio.create_task(my_coroutine())
await task
asyncio.run(main())
# 输出:
# Start
# End
9.5 元编程与反射
元编程:
- 元编程是指在运行时分析或修改程序的能力。
- Python 支持动态创建类和修改类属性或方法。
- 元编程可用于实现框架、插件系统、自动化测试等场景。
反射:
- 反射是指在运行时检查和修改程序结构的能力。
- Python 提供了多种工具来实现反射,如
getattr
,setattr
,hasattr
,dir
等函数。
示例代码:
class MyClass:
def __init__(self, x, y):
self.x = x
self.y = y
obj = MyClass(10, 20)
print(getattr(obj, 'x')) # 输出: 10
setattr(obj, 'y', 30) # 设置 obj.y 为 30
print(hasattr(obj, 'z')) # 输出: False
print(dir(obj)) # 显示 obj 的所有属性和方法