__enter__,__exit__
- 我们知道在操作文件对象的时候可以这么写
with open('a.txt') as f:
'代码块'
- 上述叫做上下文管理协议,即with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明__enter__和__exit__方法
一、上下文管理协议
class Open:
def __init__(self, name):
self.name = name
def __enter__(self):
print('出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量')
# return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('with中代码块执行完毕时执行我啊')
with Open('a.txt') as f:
print('=====>执行代码块')
# print(f,f.name)
出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量
=====>执行代码块
with中代码块执行完毕时执行我啊
- __exit__()中的三个参数分别代表异常类型,异常值和追溯信息,with语句中代码块出现异常,则with后的代码都无法执行
class Open:
def __init__(self, name):
self.name = name
def __enter__(self):
print('出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量')
def __exit__(self, exc_type, exc_val, exc_tb):
print('with中代码块执行完毕时执行我啊')
print(exc_type)
print(exc_val)
print(exc_tb)
try:
with Open('a.txt') as f:
print('=====>执行代码块')
raise AttributeError('***着火啦,救火啊***')
except Exception as e:
print(e)
出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量
=====>执行代码块
with中代码块执行完毕时执行我啊
<class 'AttributeError'>
***着火啦,救火啊***
<traceback object at 0x1065f1f88>
***着火啦,救火啊***
- 如果__exit()返回值为True,那么异常会被清空,就好像啥都没发生一样,with后的语句正常执行
class Open:
def __init__(self, name):
self.name = name
def __enter__(self):
print('出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量')
def __exit__(self, exc_type, exc_val, exc_tb):
print('with中代码块执行完毕时执行我啊')
print(exc_type)
print(exc_val)
print(exc_tb)
return True
with Open('a.txt') as f:
print('=====>执行代码块')
raise AttributeError('***着火啦,救火啊***')
print('0' * 100) #------------------------------->会执行
出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量
=====>执行代码块
with中代码块执行完毕时执行我啊
<class 'AttributeError'>
***着火啦,救火啊***
<traceback object at 0x1062ab048>
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
二、模拟open
class Open:
def __init__(self, filepath, mode='r', encoding='utf-8'):
self.filepath = filepath
self.mode = mode
self.encoding = encoding
def __enter__(self):
# print('enter')
self.f = open(self.filepath, mode=self.mode, encoding=self.encoding)
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
# print('exit')
self.f.close()
return True
def __getattr__(self, item):
return getattr(self.f, item)
with Open('a.txt', 'w') as f:
print(f)
f.write('aaaaaa')
f.wasdf #抛出异常,交给__exit__处理
<_io.TextIOWrapper name='a.txt' mode='w' encoding='utf-8'>
三、优点
使用with语句的目的就是把代码块放入with中执行,with结束后,自动完成清理工作,无须手动干预
在需要管理一些资源比如文件,网络连接和锁的编程环境中,可以在__exit__中定制自动释放资源的机制,你无须再去关系这个问题,这将大有用处
__enter__,__exit__的更多相关文章
- python - 上下文管理协议(with + __enter__ + __exit__)
上下文管理协议: with + __enter__ + __exit__ #上下问管理协议: #with + __enter__ + __exit__ class Test(): def __init ...
- __enter__,__exit__上下文管理协议
上下文管理协议__enter__,__exit__ 用途或者说好处: 1.使用with语句的目的就是把代码块放入with中执行,with结束后,自动完成清理工作,无须手动干预 2.在需要管理一些资源比 ...
- python中的__enter__ __exit__
我们前面文章介绍了迭代器和可迭代对象,这次介绍python的上下文管理.在python中实现了__enter__和__exit__方法,即支持上下文管理器协议.上下文管理器就是支持上下文管理器协议的对 ...
- with语句与__enter__,__exit__
class Foo(object): def func(self): print("func") pass def __enter__(self): print("ent ...
- __enter__,__exit__区别
__enter__():在使用with语句时调用,会话管理器在代码块开始前调用,返回值与as后的参数绑定 __exit__():会话管理器在代码块执行完成好后调用,在with语句完成时,对象销毁之前调 ...
- python-open文件处理
python内置函数open()用于打开文件和创建文件对象 语法 open(name[,mode[,bufsize]]) name:文件名 mode:指定文件的打开模式 r:只读 w:写入 a:附加 ...
- 【python】with的实现方法
来源:http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/#icomments 重点: with方法适用于需要分配和清理资 ...
- python的with...as用法
with...as叫做上下文管理器,作用是进入一个对象的作用域和离开时,可以执行执行一定的操作.这个操作是可以自己 设定的. 写个例子学习一下: class test(): def __init__( ...
- When to close cursors using MySQLdb
http://stackoverflow.com/questions/5669878/when-to-close-cursors-using-mysqldb I'm building a WSGI w ...
随机推荐
- EasyDarwin开源流媒体音视频云平台遇到的奇葩问题:内网运行正常,公网流媒体不通
最近在帮助EasyDarwin的用户部署EasyNVR+EasyDarwin云平台+EasyClient方案的过程中,遇到一个问题,EasyNVR分布在用户各地区现场的内网中,EasyDarwin云平 ...
- jquery 使用ajax,正常返回后,不执行success的问题
背景: 在使用到jQuery的ajax时,如果指定了dataType为json,老是不执行success回调,而是执行了error回调函数. 原因: 然后继续下载了几个jquery版本,如1.3.2, ...
- React深入源码--了解Redux用法之Provider
在Redux中最核心的自然是组件,以及组件相关的事件与数据流方式.但是我们在Redux中并没有采用传统的方式在getInitialState()中去初始化数据,而是采用Provider统一处理,省去了 ...
- Raspberry Pi3 ~ C语言控制串口
注明出处:http://www.cnblogs.com/einstein-2014731/p/5551846.html 使用C语言控制树莓派3B的串口,实现使用串口收发数据的目的.之前以为这个串口是被 ...
- 【转】hibernate懒加载的问题,failed to lazily initialize a collection of role
hibernate懒加载的问题,failed to lazily initialize a collection of role hibernate懒加载的问题,failed to lazily in ...
- 基于BASYS2的VHDL程序与烧写——按键消抖程序
请尊重作者版权,转载请注明源地址http://www.cnblogs.com/connorzx/p/3548364.html 按键在按下的过程中通常会产生一段时间的抖动,为了消除这种抖动,一般采取两种 ...
- ansible 自动ssh
http://szgb2016.blog.51cto.com/340201/1669731 安装 yum -y install ansible expect 生成key,ssh-keygen -t r ...
- PYTHON 爬虫笔记四:正则表达式基础用法
知识点一:正则表达式详解及其基本使用方法 什么是正则表达式 正则表达式对子符串操作的一种逻辑公式,就是事先定义好的一些特定字符.及这些特定字符的组合,组成一个‘规则字符串’,这个‘规则字符串’用来表达 ...
- 简单实现php文件管理
如何能够利用PHP语言来进行空间中的文件管理,为我们带来良好的空间布局呢?今天我们就为大家介绍一种简便的PHP文件管理的实现方法. PHP预定义变量数组种类概览 PHP uploaded_files函 ...
- codeforces 702A A. Maximum Increase(水题)
题目链接: A. Maximum Increase time limit per test 1 second memory limit per test 256 megabytes input sta ...