python——上下文管理器with

浅浅的花香味﹌ 2024-04-05 07:00 157阅读 0赞

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


在这里插入图片描述

一、open操作文件

  1. f=open('1.txt','r',encoding='utf-8')
  2. res=f.readline()
  3. print(res)
  4. f.close()
  5. res=f.readline()
  6. print(res)

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

二、使用with启动文档句柄对象的上下文管理器

  1. with open('1.txt','r',encoding='utf-8') as f1:
  2. res=f1.readline()
  3. print(res)
  4. res=f1.readline()
  5. print(res)

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

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

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

  1. class MyOpen:
  2. def __enter__(self):
  3. return 'success'
  4. def __exit__(self, exc_type, exc_val, exc_tb):
  5. print('执行结束')
  6. obj=MyOpen()
  7. with obj as f:
  8. print(f)

四、自己实现一个类支持__enter__()和__exit__()方法

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

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

执行结果

res 666666666

五、基于pymysql实现一个操作数据库的类DBClass,实现上下文管理器协议,实现退出上下文时,自动关闭游标,断开连接

  1. from pymysql import *
  2. class DBClass:
  3. def __init__(self, user, password, host, db, port, charset="utf8"):
  4. self.user = user
  5. self.password = password
  6. self.host = host
  7. self.db = db
  8. self.port = port
  9. self.charset = charset
  10. self.conn = connect(user=self.user,
  11. password=self.password,
  12. host=self.host,
  13. db=self.db,
  14. port=self.port,
  15. charset=self.charset)
  16. def __enter__(self):
  17. self.cur=self.conn.cursor()
  18. return self.cur
  19. def __exit__(self, exc_type, exc_val, exc_tb):
  20. self.cur.close()
  21. self.conn.close()
  22. if __name__ == '__main__':
  23. db=DBClass('root','root','127.0.0.1','ceshikaifa',3306)

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,157人围观)

还没有评论,来说两句吧...

相关阅读