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 ...
随机推荐
- java.lang.SuppressWarnings的注解简介
简介:java.lang.SuppressWarnings是J2SE 5.0中标准的Annotation之一.可以标注在类.字段.方法.参数.构造方法,以及局部变量上.作用:告诉编译器忽略指定的警告, ...
- Cisco interview
A. 1. Self-introduction I am Yanlin He . I am a master degree candidate of school of infomation sci ...
- 微信小程序请求数据
微信小程序请求数据,在页面展示,可以在onLoad生命周期中进行请求. 1.新建目录http,新建文件http.js 2.在js文件中暴露需要使用的变量 var baseUrl = 'http://1 ...
- Educational Codeforces Round 60 C 思维 + 二分
https://codeforces.com/contest/1117/problem/C 题意 在一个二维坐标轴上给你一个起点一个终点(x,y<=1e9),然后给你一串字符串代表每一秒的风向, ...
- 为什么行内元素不能设置margin-top/margin-bottom/padding-top/padding-bottom?
HTML 里的元素分为替换元素(replaced element)和非替换元素(non-replaced element).- 替换元素是指用作为其他内容占位符的一个元素.最典型的就是img,它只是指 ...
- Struts2--HelloWord
Struts2官网 官网指南 官网下载Struts2.5-min-lib.zip解压把lib目录下jar包拷贝到web项目lib目录下 配置web.xml文件 <filter> <f ...
- css3种引入方式,样式与长度颜色,常用样式,css选择器
# CSS三种引入方式 ## 一.三种方式的书写规范 #### 1.行间式 ```html<div style="width: 100px; height: 100px; backgr ...
- 2018-03-17 handler学习使用
1.handler具体使用https://www.cnblogs.com/JohnTsai/p/5259869.html 2.handlerThread用法https://www.jianshu.co ...
- (转)忘记wamp-mysql数据库root用户密码重置方法
转自:http://www.jb51.net/article/28883.htm 1.打开任务管理器,结束进程 mysqld-nt.exe . 2.运行命令窗口 1)进行php服务管理器安装目录中的 ...
- 《mysql必知必会》学习_第9章_20180731_欢
第九章,用正则表达式进行搜索. P52 select prod_name from products where prod_name regexp '1000' order by prod_name; ...