gdjlc

培养良好的习惯,每天一点一滴的进步,终将会有收获。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

创建一个上下文管理器类的步骤:
(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))

 

posted on 2019-07-07 22:51  gdjlc  阅读(472)  评论(0编辑  收藏  举报