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)

当使用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)

物联沃分享整理
物联沃-IOTWORD物联网 » python——上下文管理器with

发表评论