前言
在上下文管理器协议的过程中,涉及到两个魔术方法__enter__方法 和 __exit__方法
在python中所有实现了上下文管理器协议的对象 都可以用使用with操作 with启动了对象的上下文管理器上下文管理器协议:
__enter__方法: 进入enter方法返回的结果被as后面的变量接收 exit: 退出with中所有的语句执行完毕执行 执行 exit实现一个简单的文件操作来看下上下文管理器协议:
class MyOpen:
?? ?# 实例化
? ? def __init__(self, filename, mode, encoding):
? ? ? ? self.filename = filename
? ? ? ? self.mode = mode
? ? ? ? self.encoding = encoding
? ? def __enter__(self):
? ? ? ? print("---enter---方法")
? ? ? ? # 执行文件打开操作
? ? ? ? self.f = open(self.filename, self.mode, encoding=self.encoding)
? ? ? ? return self.f
? ? def __exit__(self, exc_type, exc_val, exc_tb):
? ? ? ? """
? ? ? ? :param exc_type: 异常类型
? ? ? ? :param exc_val: 异常信息
? ? ? ? :param exc_tb: 异常溯源对象
? ? ? ? :return:
? ? ? ? """
? ? ? ? print('----enter---')
? ? ? ? self.f.close()
with MyOpen('hr.txt', 'w', encoding='utf-8') as f:
? ? print(f.write('当前打开了文件,写入了数据:23323232'))
用pymysql实现一个操作数据库的类,实现上下文管理器协议,实现退出上下文时,自动关闭游标,断开连接
todo:版本1
# todo:版本1: class mysql_db(object): ? ? #实例化属性 ? ? def __init__(self):
1.连接数据库
? ? ? ? self.cou = pymysql.connect( ? ? ? ? ? ? host= "数据库主机地址", ? ? ? ? ? ? ? port= 端口, ? ? ? ? ? ? ? user="登录数据库的账号", ? ? ? ? ? ? ? password="登录数据库的密码",? ? ? ? ? ? ? database="数据库名称", ? ? ? ? ? ? ? charset='utf8', ? ? 编码格式 ? ? ? ? ? ? cursorclass=pymysql.cursors.DictCursor ? ? 将默认的元组格式转换成字典格式输出 ? ? ? ? )?
2.创建游标
? ? ? ? self.cur = self.cou.cursor()
? ? def __enter__(self):
? ? ? ? return self.cur ? ? ? 返回cur对象
? ? def __exit__(self, exc_type, exc_val, exc_tb):
? ? ? ? """
? ? ? ? :param exc_type: 异常类型
? ? ? ? :param exc_val: 异常信息
? ? ? ? :param exc_tb: 异常溯源对象
? ? ? ? :return:
? ? ? ? """
? ? ? ? #关闭游标
? ? ? ? self.cur.close()
? ? ? ?# 关闭数据库连接
? ? ? ? self.cou.close()
def Obtain_one_date():
? ? with mysql_db() as db:
? ? ? ? db.execute('select * from t_customer LIMIT 4') ? ? 使用execute方法进行查询语句
? ? ? ? content = db.fetchone() ?返回一条数据的查询的结果
? ? ? ? print(content)
# 函数调用
Obtain_one_date()
todo:版本2
sql = 'select * from t_customer LIMIT 4'
def mysql_db1(**kwargs):
? ? return pymysql.connect(host=kwargs.get('host', 'xxxx'),
? ? ? ? ? ? ? ? ? ? ? ? ? ?user=kwargs.get("user",'xxxx'),
? ? ? ? ? ? ? ? ? ? ? ? ? ?passwd=kwargs.get("passwd",'xxxx'),
? ? ? ? ? ? ? ? ? ? ? ? ? ?database=kwargs.get("database",'xxxx'),
? ? ? ? ? ? ? ? ? ? ? ? ? ?port=kwargs.get('port', xxxx),
? ? ? ? ? ? ? ? ? ? ? ? ? ?charset=kwargs.get('charset', 'utf8'))
1.创建数据库连接对象
cou = mysql_db1()
2.创建游标
with cou.cursor() as cu: ? ? cu.execute(sql) ? ? ?使用execute方法进行查询语句 ? ? commt = cu.fetchone() ? ? 返回一条数据的查询的结果 ? ? print(commt) # 函数调用 mysql_db1()
到此这篇关于python上下文管理器协议的实现的文章就介绍到这了,更多相关python上下文管理器 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
查看更多关于python上下文管理器协议的实现的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did16394