python——上下文管理器with

2年前基础语言35384
python——上下文管理器with YZL40514131 于2022-09-20 09:01:41发布 379 收藏 37 分类专栏: python 文章标签: python 开发语言 数据库 python 专栏收录该内容 78 篇文章 5 订阅 订阅专栏

CSDN话题挑战赛第2期 参赛话题:学习笔记


一、open操作文件 f=open('1.txt','r',encoding='utf-8') res=f.readline() print(res) f.close() res=f.readline() print(res)

当使用open读取文件,关闭文件,再次读取文件时报异常 ValueError: I/O operation on closed file.

二、使用with启动文档句柄对象的上下文管理器 with open('1.txt','r',encoding='utf-8') as f1: res=f1.readline() print(res) res=f1.readline() print(res)

当使用with读取文件后,在with外部再次读取文件时也会报异常 ValueError: I/O operation on closed file.

三、with打开文件为何会自动关闭?

上下文管理器协议: __enter__():进入上下文(with 操作对象时) __exit__():退出上下文(with中的代码快执行完毕之后) with是用来启动对象的上下文协议的,不是用来专门操作文件的

class MyOpen: def __enter__(self): return 'success' def __exit__(self, exc_type, exc_val, exc_tb): print('执行结束') obj=MyOpen() with obj as f: print(f) 四、自己实现一个类支持__enter__()和__exit__()方法

__enter__()方法的返回值正是输出的对象

class MyOpen: def __init__(self,filename,mode,encoding='utf-8'): self.f=open(filename,mode,encoding=encoding) def __enter__(self): return self.f def __exit__(self, exc_type, exc_val, exc_tb): self.f.close() with MyOpen('1.txt','r',encoding='utf-8') as f: res=f.readline() print("res",res)

执行结果

res 666666666

五、基于pymysql实现一个操作数据库的类DBClass,实现上下文管理器协议,实现退出上下文时,自动关闭游标,断开连接 from pymysql import * class DBClass: def __init__(self, user, password, host, db, port, charset="utf8"): self.user = user self.password = password self.host = host self.db = db self.port = port self.charset = charset self.conn = connect(user=self.user, password=self.password, host=self.host, db=self.db, port=self.port, charset=self.charset) def __enter__(self): self.cur=self.conn.cursor() return self.cur def __exit__(self, exc_type, exc_val, exc_tb): self.cur.close() self.conn.close() if __name__ == '__main__': db=DBClass('root','root','127.0.0.1','ceshikaifa',3306)

相关文章

排序算法 | 快排、冒泡、堆排、归并、基数、递归、希尔、计数

排序算法 | 快排、冒泡、堆排、归并、基数、递归、希尔、计数...

基于WEB的网上购物系统的设计与实现(附:源码 论文 sql文件)

基于WEB的网上购物系统的设计与实现(附:源码 论文 sql文件)...

大数据ETL开发之图解Kettle工具(入门到精通)

大数据ETL开发之图解Kettle工具(入门到精通)...

【C++初阶】C++入门(一)

【C++初阶】C++入门(一)...

uniapp开发微信小程序,从构建到上线

uniapp开发微信小程序,从构建到上线...

SpringBoot 整合 Elasticsearch (超详细)

SpringBoot 整合 Elasticsearch (超详细)...