• 我们知道在操作文件对象的时候可以这么写
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'>

三、优点

  1. 使用with语句的目的就是把代码块放入with中执行,with结束后,自动完成清理工作,无须手动干预

  2. 在需要管理一些资源比如文件,网络连接和锁的编程环境中,可以在__exit__中定制自动释放资源的机制,你无须再去关系这个问题,这将大有用处

__enter__,__exit__的更多相关文章

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

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

  2. __enter__,__exit__上下文管理协议

    上下文管理协议__enter__,__exit__ 用途或者说好处: 1.使用with语句的目的就是把代码块放入with中执行,with结束后,自动完成清理工作,无须手动干预 2.在需要管理一些资源比 ...

  3. python中的__enter__ __exit__

    我们前面文章介绍了迭代器和可迭代对象,这次介绍python的上下文管理.在python中实现了__enter__和__exit__方法,即支持上下文管理器协议.上下文管理器就是支持上下文管理器协议的对 ...

  4. with语句与__enter__,__exit__

    class Foo(object): def func(self): print("func") pass def __enter__(self): print("ent ...

  5. __enter__,__exit__区别

    __enter__():在使用with语句时调用,会话管理器在代码块开始前调用,返回值与as后的参数绑定 __exit__():会话管理器在代码块执行完成好后调用,在with语句完成时,对象销毁之前调 ...

  6. python-open文件处理

    python内置函数open()用于打开文件和创建文件对象 语法 open(name[,mode[,bufsize]]) name:文件名 mode:指定文件的打开模式 r:只读 w:写入 a:附加 ...

  7. 【python】with的实现方法

    来源:http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/#icomments 重点: with方法适用于需要分配和清理资 ...

  8. python的with...as用法

    with...as叫做上下文管理器,作用是进入一个对象的作用域和离开时,可以执行执行一定的操作.这个操作是可以自己 设定的. 写个例子学习一下: class test(): def __init__( ...

  9. When to close cursors using MySQLdb

    http://stackoverflow.com/questions/5669878/when-to-close-cursors-using-mysqldb I'm building a WSGI w ...

随机推荐

  1. 九度OJ 1132:与7无关的数 (数字特性)

    时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:1619 解决:1037 题目描述: 一个正整数,如果它能被7整除,或者它的十进制表示法中某个位数上的数字为7, 则称其为与7相关的数.现求所 ...

  2. go签名算法设计

    Go by Example 中文:Base64编码 https://books.studygolang.com/gobyexample/base64-encoding/

  3. aop学习总结三----aop的相关概念

    aop学习总结三----aop的相关概念 public Object invoke(Object proxy, Method method, Object[] args) throws Throwab ...

  4. java之折半查找

    //功能:二分查找import java.util.*; public class Demo1 { public static void main(String[] args) { int arr[] ...

  5. db的操作

    '/---------------------------------------------------------------------------------------------- '/ ...

  6. SpringBoot-(8)-配置MySQL数据库链接,配置数据坚挺拦截,创建默认数据表

    一,链接mysql数据库 # 数据源基本配置 spring.datasource.username=root spring.datasource.password=123456 spring.data ...

  7. Mac下文件编码转换

    参见:http://bbs.feng.com/read-htm-tid-107633.html 使用: sudo find *.txt -exec sh -c "iconv -f GB180 ...

  8. /dev/sda2 is mounted; will not make a filesystem here!

    一定要记住,不可以在分区挂载之后再进行格式化!!在错误提示当中可以看出你的分区已经挂载了.先将这个分区卸载了再重新格式化:umount /dev/sda2mkfs.ext2 /dev/sda2这样就没 ...

  9. backbone测试代码

    一.入门测试 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...

  10. MYSQL进阶学习笔记十七:MySQL定期维护!(视频序号:进阶_36)

    知识点十八:MySQL定期维护(37) 一.Mysql的定时器 所谓的定时器,指的是在某个时间段去执行同样的代码.比如闹钟.每到指定的时间闹铃就会响.同样的,我们这个定时器,只要满足我们的一个定时条件 ...