本文共 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/