Python上下文管理器的使用

上下文管理器可以控制代码块执行前的准备动作,以及执行后的清理动作。

创建一个上下文管理器类的步骤:
(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))
原文地址:https://www.cnblogs.com/gdjlc/p/11148605.html