美文网首页
上下文管理器-with

上下文管理器-with

作者: 测试探索 | 来源:发表于2022-11-26 13:46 被阅读0次

    一:with做了什么

    with启动了对象的上下文管理器
    

    二:上下文管理器协议:

    __enter__:进入
        enter方法返回的结果,被as后面的变量接受,with ... as f
    __exit__:退出
        with中所有的语句执行完毕后,执行该方法
    

    在python中所有实现了上下文管理器协议的对象,都可以使用with操作

    三、初识

    f = open("musen.txt","w")
    f.close()
    print("f的dir方法:",dir(f))
    
    # 等同于如下
     with open("test.txt","w") as f:
         f.write("python")
    
    image.png

    四:自定义文件操作的上下文管理器协议

    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(exc_type)
            print(exc_val)
            print(exc_tb)
            self.f.close()
            print("--exit--方法")
    
    with MyOpen("musen.txt","w",encoding = "utf-8") as f:
        print(f.write('e23433 '))
        # print(bbb)
    
    print("-----end------")
    
    image.png

    相关文章

      网友评论

          本文标题:上下文管理器-with

          本文链接:https://www.haomeiwen.com/subject/ovtqfdtx.html