• python——上下文管理器with


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


    在这里插入图片描述

    一、open操作文件

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

    当使用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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    当使用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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    四、自己实现一个类支持__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)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    执行结果

    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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    在这里插入图片描述

  • 相关阅读:
    从零开始配置 vim(14)——目录管理插件
    基于标准库的STM32的外部中断EXTI
    SpringBoot中静态变量注入方案,一网打尽
    38Java Math类
    云计算安全的新挑战:零信任架构的应用
    Vue响应式系统的基本原理
    【PHP函数封装】分分钟帮你实现数据脱敏处理, 支持手机号码、邮箱、身份证号 中文字符串!
    High-Resolution Network (篇一):原理刨析
    看了这篇不用再苦恼如何将视频压缩了
    初识进程以及父子进程
  • 原文地址:https://blog.csdn.net/YZL40514131/article/details/126818274