我们前面文章介绍了迭代器和可迭代对象,这次介绍python的上下文管理。在python中实现了__enter__和__exit__方法,即支持上下文管理器协议。上下文管理器就是支持上下文管理器协议的对象,它是为了with而生。当with语句在开始运行时,会在上下文管理器对象上调用 __enter__ 方法。with语句运行结束后,会在上下文管理器对象上调用 __exit__ 方法

with的语法:

with EXPR as VAR:
BLOCK

这是上面语法的伪代码:

mgr = (EXPR)
exit = type(mgr).__exit__ # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
try:
VAR = value # Only if "as VAR" is present
BLOCK
except:
# The exceptional case is handled here
exc = False
if not exit(mgr, *sys.exc_info()):
raise
# The exception is swallowed if exit() returns true
finally:
# The normal and non-local-goto cases are handled here
if exc:
exit(mgr, None, None, None)

1、生成上下文管理器mgr
2、如果没有发现__exit__, __enter__两个方法,解释器会抛出AttributeError异常
3、调用上下文管理器的 __enter__() 方法
4、如果语法里的as VAR没有写,那么 伪代码里的 VAR= 这部分也会同样被忽略
5、如果BLOCK中的代码正常结束,或者是通过break, continue ,return 来结束,__exit__()会使用三个None的参数来返回
6、如果执行过程中出现异常,则使用 sys.exc_info的异常信息为参数调用 __exit__(exc_type, exc_value, exc_traceback)

之前我们对文件的操作是这样的:

try:
f = open('filename')
except:
print("Unexpected error:", sys.exc_info()[0])
else:
print(f.readlines())
f.close()

现在有了with语句可以使代码更加简洁,减少编码量,下面的语句会在执行完后自动关闭文件(即使出现异常也会)。:

with open('example.info', 'r') as f:
print(f.readlines())

一个例子:

class TmpTest:
def __init__(self,filename):
self.filename=filename
def __enter__(self):
self.f = open(self.filename, 'r')
# return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
self.f.close() test=TmpTest('file') with test as t:
print ('test result: {}'.format(t))

返回:

test result: None

这个例子里面__enter__没有返回,所以with语句里的"as t"到的是None,修改一下上面的例子:

class TmpTest:
def __init__(self,filename):
self.filename=filename
def __enter__(self):
self.f = open(self.filename, 'r')
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
self.f.close() test=TmpTest('file') with test as t:
print ('test result: {}'.format(t))

返回:

test result: <_io.TextIOWrapper name='file' mode='r' encoding='cp936'>

如果在__init__或者__enter__中抛出异常,则不会进入到__exit__中:

class TmpTest:
def __init__(self,filename):
self.filename=filename
print("__init__")
raise ImportError
def __enter__(self):
self.f = open(self.filename, 'r')
print("__enter__")
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
print("__exit__")
self.f.close() test=TmpTest('file')
with test as t:
print ('test result: {}'.format(t))

返回:

__init__
Traceback (most recent call last):
File "D:/pythonScript/leetcode/leetcode.py", line 14, in <module>
test=TmpTest('file')
File "D:/pythonScript/leetcode/leetcode.py", line 5, in __init__
raise ImportError
ImportError

如果在__exit__中返回True,则不会产生异常:

class TmpTest:
def __init__(self,filename):
self.filename=filename
print("__init__") def __enter__(self):
self.f = open(self.filename, 'r')
print("__enter__")
return self.f def __exit__(self, exc_type, exc_val, exc_tb):
print("__exit__ {} ".format(exc_type))
self.f.close()
return True test=TmpTest('file')
with test as t:
print ('test result: {}'.format(t))
raise ImportError
print("no error")

返回:

__init__
__enter__
test result: <_io.TextIOWrapper name='file' mode='r' encoding='cp936'>
__exit__ <class 'ImportError'>
no error

参考: https://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p03_make_objects_support_context_management_protocol.html?highlight=with
        https://docs.python.org/3/library/stdtypes.html#typecontextmanager
        https://www.python.org/dev/peps/pep-0343/

python中的__enter__ __exit__的更多相关文章

  1. python - 上下文管理协议(with + __enter__ + __exit__)

    上下文管理协议: with + __enter__ + __exit__ #上下问管理协议: #with + __enter__ + __exit__ class Test(): def __init ...

  2. python中那些双下划线开头得函数和变量--转载

    Python中下划线---完全解读     Python 用下划线作为变量前缀和后缀指定特殊变量 _xxx 不能用'from module import *'导入 __xxx__ 系统定义名字 __x ...

  3. Python中异常(Exception)的总结

    Python中的异常处理 异常处理的语句结构 try: <statements> #运行try语句块,并试图捕获异常 except <name1>: <statement ...

  4. Python中With的用法

    在看Dive Into Python中有关描述文件读写那章节的时候,看到了有关with的用法,查阅下相关资料,记录下来,以备后用. 官方的reference上有关with statement是这样说的 ...

  5. python中with学习

    python中with是非常强大的一个管理器,我个人的理解就是,我们可以通过在我们的类里面自定义enter(self)和exit(self,err_type,err_value,err_tb)这两个内 ...

  6. Python中的上下文管理器和with语句

    Python2.5之后引入了上下文管理器(context manager),算是Python的黑魔法之一,它用于规定某个对象的使用范围.本文是针对于该功能的思考总结. 为什么需要上下文管理器? 首先, ...

  7. 整理一下python中with的用法

    ith替代了之前在python里使用try...finally来做清理工作的方法.基本形式如下: with expression [as variable]: with-block 当expressi ...

  8. python python中那些双下划线开头的那些函数都是干啥用用的

    1.写在前面 今天遇到了__slots__,,所以我就想了解下python中那些双下划线开头的那些函数都是干啥用用的,翻到了下面这篇博客,看着很全面,我只了解其中的一部分,还不敢乱下定义. 其实如果足 ...

  9. python中那些双下划线开头得函数和变量

    Python中下划线---完全解读     Python 用下划线作为变量前缀和后缀指定特殊变量 _xxx 不能用’from module import *’导入 __xxx__ 系统定义名字 __x ...

随机推荐

  1. 科普贴 | 以太坊网络中的Gas Limit 和 Gas Price 是什么概念?

    接触以太坊的同学都听过 Gas/ Gas Price/ Gas Limit,那么这些词汇究竟是什么意思? 还有,为什么有时候你的ETH转账会很慢?如何提高ETH转账速度? Ethereum平台 Vit ...

  2. dp算法之平安果路径问题c++

    前文:https://www.cnblogs.com/ljy1227476113/p/9563101.html 在此基础上更新了可以看到行走路径的代码. 代码: #include <iostre ...

  3. 初次接触OSSEC

    OSSEC是一款开源的系统监控平台.它集成了HIDS(主机入侵检测).日志监控.安全事件管理(SIM).安全信息和事件管理(SIEM)于一身,结构简单.功能强大的开源解决方案. 主要优点 满足合规性 ...

  4. 微软职位内部推荐-Senior BSP Engineer

    微软近期Open的职位: The position of Sr. BSP engineer requires experience and good knowledge in mobile hardw ...

  5. Linux第五章笔记

    5.1 与内核通信 系统调用在用户空间进程和硬件设备之间添加了一个中间层. 主要作用有: 为用户空间提供了一种硬件的抽象接口 系统调用保证了系统的稳定和安全 每个进程都需要运行在虚拟机内 5.2 AP ...

  6. 冲刺Two之站立会议3

    今天继续昨天的工作,对主界面进行设计优化,并成功将各个按钮和对应的功能模块连接了起来.并对服务器部分进行了部分改进,包括登录界面的美观性和服务器数据库部分的处理.

  7. 第二阶段Sprint8

    昨天:把视频录制整合到时间提醒里,实现视频提醒 今天:重新规划主界面,把视频录制暂放到主页面里,先实现功能,视频提醒后期再做. 遇到的问题:还是有问题,虽然能运行,但是只能播放,不能录了啊...

  8. 关于断言(Assert)

    断言,字面上的意思大致是十分肯定的说,也就是说我们相信这个结果是真的.如果我们的断言不为真,那这个这个结果就和我们预期的结果不一样.在编程上同理,如果程序运行出来的结果和你想要的结果不一致,那你的程序 ...

  9. Linux命令(二十一) 改变文件所有权 chown 和 chgrp

    目录 1.命令简介 2.常用参数介绍 3.实例 4.直达底部 命令简介 一个文件属于特定的所有者,如果更改文件的属主或属组可以使用 chown 和 chgrp 命令. chown 命令可以将文件变更为 ...

  10. Docker run centos 内部使用systemctl 启动服务的方法

    1. 执行docker 镜像 使用命令为 docker run --privileged=true -ti -e "container=docker" centos /usr/sb ...