- 作者:老汪软件技巧
- 发表时间:2024-09-07 10:03
- 浏览量:
1. 上下文管理器简介2. 使用内置的上下文管理器
with open("example.txt", "w") as file:
file.write("Hello, world!")
3. 上下文管理器的工作原理4. 自定义简单的上下文管理器
class SimpleContextManager:
def __enter__(self):
print("进入上下文管理器")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("退出上下文管理器")
with SimpleContextManager():
print("执行上下文中的代码")
5. 上下文管理器的实际应用
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
if self.file:
self.file.close()
with FileManager("example.txt", "w") as file:
file.write("Hello, world!")
class DatabaseConnection:
def __enter__(self):
print("打开数据库连接")
self.connection = "Database connection"
return self.connection
def __exit__(self, exc_type, exc_value, traceback):
print("关闭数据库连接")
self.connection = None
with DatabaseConnection() as conn:
print(f"正在使用:{conn}")
class ExceptionHandlingContextManager:
def __enter__(self):
print("进入上下文")
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
print(f"捕获异常:{exc_value}")
return True # 阻止异常传播
print("正常退出上下文")
with ExceptionHandlingContextManager():
print("执行代码块")
raise ValueError("这是一场异常")
6. 通过生成器定义上下文管理器
from contextlib import contextmanager
@contextmanager
def simple_context_manager():
print("进入上下文")
yield
print("退出上下文")
with simple_context_manager():
print("执行代码块")
7. 使用生成器实现文件管理器
from contextlib import contextmanager
@contextmanager
def file_manager(filename, mode):
file = open(filename, mode)
try:
yield file
finally:
file.close()
with file_manager("example.txt", "w") as file:
file.write("Hello, world!")
8. 上下文管理器的嵌套使用
from contextlib import contextmanager
@contextmanager
def manager_one():
print("进入第一个上下文")
yield
print("退出第一个上下文")
@contextmanager
def manager_two():
print("进入第二个上下文")
yield
print("退出第二个上下文")
with manager_one(), manager_two():
print("执行代码块")
总结
本文介绍了Python中的上下文管理器及其在资源管理中的重要作用。通过具体的示例,展示了如何使用 __enter__ 和 __exit__ 方法来自定义上下文管理器,以便在进入和退出代码块时自动执行特定操作,如管理文件、数据库连接等。此外,还介绍了通过 @contextmanager 装饰器使用生成器函数简化上下文管理器的定义方式。还讨论了上下文管理器的嵌套使用,可以在一个 with 语句中同时管理多个资源。掌握这些技术,能够帮助大家编写更加高效、可维护的Python代码,从而确保资源的正确管理和释放。