首先理解什么是上下文管理器。
一种用于管理资源的对象。
通过实现 __enter__() 和 __exit__() 方法来确保资源被正确地获取和释放,无论代码块中是否发生异常。
说白了就是有打开和关上的操作的一个东西。
案例:文件操作
with open("example.txt", "w") as file:
file.write("Hello, World!")
-
open("example.txt", "w")创建了一个文件对象,这个文件对象是一个上下文管理器。 -
__enter__()方法被调用,打开文件并返回文件对象赋值给file。 -
在
with代码块中,可以使用file变量来写入文件。 -
当退出
with代码块时,__exit__()方法被调用,关闭文件。
案例:数据库连接管理
class DatabaseConnection:
def __init__(self, db_name):
self.db_name = db_name
self.connection = None
def __enter__(self):
print(f"Connecting to database {self.db_name}...")
# 模拟连接数据库
self.connection = f"Connection to {self.db_name}"
return self.connection # 返回数据库连接对象
def __exit__(self, exc_type, exc_val, exc_tb):
print(f"Closing connection to database {self.db_name}...")
# 模拟关闭数据库连接
self.connection = None
# 使用 with as 语句管理数据库连接
with DatabaseConnection("my_database") as db_conn:
print(f"Database connection: {db_conn}")
# 在这里执行数据库操作
案例:线程池管理
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=24) as executor:
# 提交任务到线程池
future = executor.submit(lambda x: x * x, 2)
print(future.result()) # Output: 4
with...as...是一种用于资源管理的语法结构。
代码示例:
with open("example.txt", "r") as file:
content = file.read()
print(content)
open("example.txt", "r")返回一个文件对象with语句自动调用文件对象的__enter__()方法获取资源- 打开文件,返回文件对象赋值给
file - 在代码块内部对文件进行读取操作
- 自动调用文件对象的
__exit__()方法,关闭文件
with后面加上下文管理器(context manager),可以是类,也可以是具体对象。
代码示例:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=24) as executor:
# 在这个代码块中,可以使用 executor 来提交任务
future = executor.submit(lambda x: x * x, 2)
print(future.result()) # Output: 4
上文中open()是一个具体对象实例,但此处ThreadPoolExecutor 是一个类。
当使用 with ThreadPoolExecutor(max_workers=24) as executor 时,ThreadPoolExecutor(max_workers=24) 创建了一个 ThreadPoolExecutor 类的实例,这个实例就是一个上下文管理器。
as 后面加一个变量名,用于接收上下文管理器的 __enter__() 方法返回的对象。
比如在前述open代码块中,可以通过 file 这个变量来读取文件内容。
再比如前述thread代码块中,可以通过executor来使用线程池管理器ThreadPoolExecutor的所有方法,比如executor.submit(函数名,参数)来执行多线程。

被折叠的 条评论
为什么被折叠?



