Python上下文管理协议:__enter__和__exit__
上下文管理器(context manager)是Python2.5开始支持的一种语法,用于规定某个对象的使用范围。一旦进入或者离开该使用范围,会有特殊操作被调用 (比如为对象分配或者释放内存)。它的语法形式是with...as...
所谓上下文管理协议,就是咱们打开文件时常用的一种方法:with
__enter__(self):当with开始运行的时候触发此方法的运行
__exit__(self, exc_type, exc_val, exc_tb):当with运行结束之后触发此方法的运行
exc_type如果抛出异常,这里获取异常的类型
exc_val如果抛出异常,这里显示异常内容
exc_tb如果抛出异常,这里显示所在位置
代码示例:
class Sample:
def __enter__(self):
print "In __enter__()"
return "Foo" def __exit__(self, type, value, trace):
print "In __exit__()" def get_sample():
return Sample() with get_sample() as sample:
print "sample:", sample
输出如下:
In __enter__()
sample: Foo
In __exit__()
__enter__()
方法被执行
__enter__()
方法返回的值 - 这个例子中是”Foo”,赋值给变量’sample’
执行代码块,打印变量”sample”的值为 “Foo”
__exit__()
方法被调用
改一下代码,看看具体如何工作的:
class Sample:
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print "type:", type
print "value:", value
print "trace:", trace def do_something(self):
bar = 1/0
return bar + 10 with Sample() as sample:
sample.do_something()
代码执行后:
type: <type 'exceptions.ZeroDivisionError'>
value: integer division or modulo by zero
trace: <traceback object at 0x1004a8128>
Traceback (most recent call last):
File "./with_example02.py", line 19, in <module>
sample.do_somet hing()
File "./with_example02.py", line 15, in do_something
bar = 1/0
ZeroDivisionError: integer division or modulo by zero
开发库时,清理资源,关闭文件等等操作,都可以放在__exit__
方法当中。因此,Python的with语句是提供一个有效的机制,让代码更简练,同时在异常产生时,清理工作更简单。
Python上下文管理协议:__enter__和__exit__的更多相关文章
- python基础----实现上下文管理协议__enter__和__exit__
我们知道在操作文件对象的时候可以这么写 with open('a.txt') as f: '代码块' 上述叫做上下文管理协议,即with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明_ ...
- Python 上下文管理协议中的__enter__和__exit__基本理解
所谓上下文管理协议,就是咱们打开文件时常用的一种方法:with __enter__(self):当with开始运行的时候触发此方法的运行 __exit__(self, exc_type, exc_va ...
- python - 上下文管理协议(with + __enter__ + __exit__)
上下文管理协议: with + __enter__ + __exit__ #上下问管理协议: #with + __enter__ + __exit__ class Test(): def __init ...
- 上下文管理器之__enter__和__exit__
目录 前言 with as是如何工作的 自定制open方法 更多的示例 返回主目录 前言 回到顶部 有个学生在第四轮面试中被CTO问到:如何自定义实现with open的功能.然后就一脸懵逼的回来找我 ...
- python上下文管理协议
所谓上下文管理协议,就是咱们打开文件时常用的一种方法:with __enter__(self):当with开始运行的时候触发此方法的运行 __exit__(self, exc_type, exc_va ...
- python上下文管理协议,即with的详细使用
一.with obj as f: #代码块... 二.执行流程: 1.with obj --->触发obj.__enter__(),需要在obj里写__enter__(self),在它里边写返回 ...
- __enter__,__exit__上下文管理协议
上下文管理协议__enter__,__exit__ 用途或者说好处: 1.使用with语句的目的就是把代码块放入with中执行,with结束后,自动完成清理工作,无须手动干预 2.在需要管理一些资源比 ...
- Python概念-上下文管理协议中的__enter__和__exit__
所谓上下文管理协议,就是咱们打开文件时常用的一种方法:with __enter__(self):当with开始运行的时候触发此方法的运行 __exit__(self, exc_type, exc_va ...
- 上下文管理协议with_open,__enter__和__exit__(三十八)
在操作文件对象的时候可以这么写 with open('a.txt') as f: '代码块' 上述叫做上下文管理协议,即with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明__ent ...
随机推荐
- mysql 5.7 修改密码
mysql 5.7 ,user表就没有password 这个字段了. ') where user='root' and host='localhost'; 这样当然就改不了密码了. ') where ...
- Pappus一阶矩公式
- jquery checkbox反复调用attr('checked', true/false)只有第一次生效 Jquery 中 $('obj').attr('checked',true)失效的几种解决方案
1.$('obj').prop('checked',true) 2. $(':checkbox').each(function(){ this.checked=true; }) 为什么:attr为失效 ...
- matlab中的结构体
今天用imfinfo函数 >> K = imfinfo(‘colorbar_copy1.jpg’) K = 包含以下字段的 struct: Filename: 'E:\matlab\col ...
- ASP.NET 压缩输出的HTML字符
重写Render using System; using System.Collections.Generic; using System.Text; using System.Web.UI; usi ...
- java http大文件断点续传上传
因为需要研究下断点上传的问题.找了很久终于找到一个比较好的项目. 效果: 上传中,显示进度,时间,百分比. 点击[Pause]暂停,点击[Resume]继续. 2,代码分析 项目进行了封装使用最简单的 ...
- LRU ,LRUW,CKPT-Q
原文出处:http://www.itpub.net/thread-1631537-1-1.html http://www.linuxidc.com/Linux/2012-07/66767.htm ...
- multiprocessing、threading、gevent区别
1. 进程是资源分配的单位 2. 线程是操作系统调度的单位 3. 进程切换需要的资源很最大,效率很低 4. 线程切换需要的资源一般,效率一般(当然了在不考虑GIL的情况下) 5. 协程切换任务资源很小 ...
- CentOS 网络设置修改 2
一.CentOS 修改IP地址 修改对应网卡的IP地址的配置文件# vi /etc/sysconfig/network-scripts/ifcfg-eth0 修改以下内容 DEVICE=eth0 #描 ...
- centos修改主机名命令
centos修改主机名命令 需要修改两处:一处是/etc/sysconfig/network,另一处是/etc/hosts,只修改任一处会导致系统启动异常.首先切换到root用户. vi / ...