zoukankan      html  css  js  c++  java
  • Python概念-上下文管理协议中的__enter__和__exit__

    所谓上下文管理协议,就是咱们打开文件时常用的一种方法:with

    __enter__(self):当with开始运行的时候触发此方法的运行

    __exit__(self, exc_type, exc_val, exc_tb):当with运行结束之后触发此方法的运行

    exc_type如果抛出异常,这里获取异常的类型 

    exc_val如果抛出异常,这里显示异常内容

    exc_tb如果抛出异常,这里显示所在位置

    代码示例:(以自己定义的Open类型做示例)

     1 # 编辑者:闫龙
     2 class Open:
     3     def __init__(self,filename,mode,encoding): #在实例化Open的时候传入文件名称,打开方式,编码格式
     4         self.filename = filename
     5         self.mode = mode
     6         self.encoding = encoding
     7         #使用系统函数open()传入相应打开文件所需的参数,将文件句柄传递给self.file
     8         self.file = open(filename,mode=mode,encoding=encoding)#这里我总感觉是在作弊
     9     def read(self):#自己定义read方法
    10         return self.file.read()#返回self.file文件句柄read()的值
    11     def write(self,Context):#自己定义write方法
    12         self.file.write(Context+"
    ")#使用self.file文件句柄write方法将内容写入文件
    13         print(Context,"已写入文件",self.filename)
    14     # 利用__getattr__(),Attr系列中的getattr,当对象没有找到Open中传递过来的名字时,调用此方法
    15     def __getattr__(self, item):
    16         return getattr(self.file,item)#返回self.file文件句柄中,被对象调用,切在Open类中没有的名字
    17     def __enter__(self):
    18         return self
    19     def __exit__(self, exc_type, exc_val, exc_tb):
    20         self.file.close()
    21         print("文件已经关闭")
    22 
    23 # MyFile = Open("a.txt","w+","utf8")
    24 # MyFile.write("Egon is SomeBody")
    25 # MyFile.close()
    26 # MyFile = Open("a.txt","r+","utf8")
    27 # print(MyFile.read())
    28 # MyFile.seek(0)
    29 # print(MyFile.readline())
    30 # MyFile.close()
    31 
    32 with Open("a.txt","r+","utf8")  as  egon:
    33     print(egon.read())
  • 相关阅读:
    go反射实现实体映射
    golang的time包:秒、毫秒、纳秒时间戳输出
    在 Gin 框架中使用 JWT 认证
    docker安装redis
    docker安装mysql5.7
    Python Web实战:Python+Django+MySQL实现基于Web版的增删改查
    apache2.4配置weblogic12c集群(linux环境)
    小BUG大原理:重写WebMvcConfigurationSupport后SpringBoot自动配置失效
    Spring源码解析02:Spring IOC容器之XmlBeanFactory启动流程分析和源码解析
    Git进阶:常用命令和问题案例整理
  • 原文地址:https://www.cnblogs.com/DragonFire/p/6764066.html
Copyright © 2011-2022 走看看