博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python中的上下文管理协议 __enter__ __exit__
阅读量:4211 次
发布时间:2019-05-26

本文共 774 字,大约阅读时间需要 2 分钟。

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

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

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

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

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

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

class AttrScope(object):    Current=None    def __init__(self):        self.attr={1:2}        self.old_scope=None    def __enter__(self):        print("__enter__")        self.old_scope=AttrScope.Current        self.attr={2:3}        AttrScope.Current=self        return self    def __exit__(self, exc_type, exc_val, exc_tb):        assert self.old_scope        AttrScope.Current=self.old_scopeAttrScope.Current=AttrScope()a=AttrScope()print("begin with:",a.Current.attr)with a:    print("ha")print(a.attr)print(a.Current.attr)

输出:

begin with: {1: 2}__enter__ha{2: 3}{1: 2}

转载地址:http://ibwmi.baihongyu.com/

你可能感兴趣的文章
Linux学习记录--文件|目录的默认权限与隐藏权限
查看>>
Linux学习记录--命令与文件的查询
查看>>
Linux命令缩写
查看>>
Linux学习记录--文件系统简介
查看>>
Linux学习记录--文件系统简单操作
查看>>
Linux学习记录--磁盘分区,格式化与检验
查看>>
Linux学习记录--磁盘挂载与卸载
查看>>
Linux学习记录--内存交换空间的构建
查看>>
Linux学习记录--文件压缩
查看>>
Linux学习记录--文件备份|还原
查看>>
ASCII、ANSI、Unicode及UTF-8编码
查看>>
Unicode,ANSI,UTF-8的故事
查看>>
ANSI、Unicode、UTF-8、DBCS等字符集及相关数据类型、函数的区别
查看>>
Linux学习记录--vim与vi常用命令
查看>>
Linux学习记录--shell介绍
查看>>
Linux学习记录--shell变量
查看>>
Linux学习记录--命名别名与历史命令
查看>>
Linux学习记录--数据流重定向
查看>>
Linux学习记录--管道命令
查看>>
Linux学习记录--正则表达式与其应用
查看>>