上下文管理器可以控制代码块执行前的准备动作,以及执行后的清理动作。
创建一个上下文管理器类的步骤:
(1)一个__init__方法,来完成初始化(可选)
(2)一个__enter__方法,来完成所有建立工作
(3)一个__exit__方法,来完成所有清理工作
例子1:
class User():
def __init__(self):
print('实例化')
def __enter__(self):
print('进入')
def __exit__(self, exc_type, exc_val, exc_trace):
print('退出')
obj = User()
with obj:
print('主要内容')
运行结果:
实例化
进入
主要内容
退出
例子2:操作MySql数据库
import mysql.connector
class UseDatabase:
def __init__(self, config:dict) -> None:
self.configuration = config
def __enter__(self) -> 'cursor':
self.conn = mysql.connector.connect(**self.configuration)
self.cursor = self.conn.cursor()
return self.cursor
def __exit__(self, exc_ype, exc_value, exc_trace) -> None:
self.conn.commit()
self.cursor.close()
self.conn.close()
dbconfig = {'host':'127.0.0.1',
'user':'root',
'password':'',
'database':'testdb',}
with UseDatabase(dbconfig) as cursor:
_SQL = """insert into user(name,age)
values(%s,%s)"""
cursor.execute(_SQL, ('张三',22))
本文介绍了Python上下文管理器的使用,它负责代码执行前的准备工作和执行后的清理任务。通过实现`__enter__`和`__exit__`方法,我们可以自定义资源管理的生命周期。文中给出了两个例子,一个是基本的使用示例,另一个是应用于操作MySQL数据库的情景。

763

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



