__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 ...
随机推荐
- 清理yum 缓存
两条命令 yum clean all 以及 rm -rf /var/cache/yum/* 如何有效的清理yum缓存 - CSDN博客 https://blog.csdn.net/nsrainbow/ ...
- Congruent Matrices
http://mathworld.wolfram.com/CongruentMatrices.html Two square matrices and are called congruent i ...
- some base knowledge
har类型的长度被定义为一个8位字节,这很简单. short类型的长度至少为两字节.在有些计算机上,对于有些编译程序,short类型的长度可能为4字节,或者更长. int类型是一个整数的“自然”大小, ...
- TMS320C6478+MCP2515
调一个驱动,将看过的资料记录下来. 这个驱动写得比较直观:http://www.51hei.com/bbs/dpj-114085-1.html
- linux apache服务器
apache服务器 服务端功能是侦听和响应客户端的http请求.http协议的默认端口是80. 1996年以来,apache成为最流行的web服务器. IIS web服务器只能安装在windows上. ...
- codeforces776E
传送门 这题看着很唬人,但实际上是道水题... f[n]通过打表或证明,可以发现就是欧拉函数,g[n]恒等于n,所以题目的意思就是让你求n的k次欧拉函数. 可以发现实际上k次欧拉函数,n的数值减小得很 ...
- 一个测试基础面试题——如何测试web银行开户
之前面试被问到过这样一个问题,自己答的都是一些UI界面上的case,看了一些大神的关于这类面试题的总结才知道自己差的不是一点半点,今天也总结下. 内管银行开户,有账号.用户名.用户证件类型.证件号三个 ...
- 最小点覆盖 hdu--1054
点击打开题目链接 最小点覆盖=最大二分匹配的 (单向图) ; 最小点覆盖=最大二分匹配的一半 (双向图) ; 证明 所以我们只需求最大匹配,用 匈牙利算法 求出最大匹配,除以二得到答案 具体算法都已经 ...
- python装饰器精髓代码
#!/usr/bin/env python #-*- coding:utf-8 -*- import time def foo(func): def inner(): print('fs...') f ...
- oracle下 启动subversion命令 及 oracle相关服务启动备忘
linux shell下 svnserve - d -r + 目录 例如:svnserve -d -r /svn 启动 svn服务. 访问svn://192.168.0.120/kjcg 测试. ...