python学习笔记 with语句
来源:互联网 发布:桌面日历记事本软件 编辑:程序博客网 时间:2024/06/05 09:09
理解Python中的with语句:
有一些任务可能实现需要设置,时候需要做清理工作,对于这种场景,Python的with语句是一种非常好的处理方式,一个好的例子是文件处理,你需要获取一个文件句柄,从文件中读取数据,操作文件,最后关闭文件句柄。如果不用with语句的代码就是如下方法:
file=open('test.txt')
data=file.read()
file.close()
这里就存在两个问题,一个是文件可能忘记关闭文件句柄,而是文件读取可能出现异常没有处理。于是就产生如下方法:
file=open('test.txt')
try:
data=file.read()
finally:
file.close()
但是无疑这样的代码过于臃肿,于是引入with语句 只需要如下两句即可:
with open('test.txt') as file:
data=file.read()
这样的代码无疑简单易懂,那么with是怎样工作的呢?:基本思想是with所求值的对象必须有一个__enter__() 和__exit__() 方法,紧跟着with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将赋值给as后面的变量。当with后面的代码块全部被执行完毕后,将调用前面返回对象的__exit__()方法参照如下:
#!/usr/bin/env/python
#-*-coding:utf-8-*-
#with_example.py
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__()
可见首先
1:get__sample()运行得到一个为Sample类的对象实例
2:这个对象的 __enter__()方法被调用 返回一个字符串 'foo'
3:然后将这个字符串赋值给 sample 这个变量,
4:现在sample保存了'foo' 这个字符串,继续运行 print 'sample',sample 这个对象
5:最后调用最开始得到的Sample对象实例的 __exit__() 方法
#!/usr/bin/env/python
#-*-coding:utf-8-*-
#with_example2.py
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()
#!/usr/bin/env/python
#-*-coding:utf-8-*-
#with_example2.py
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()
在这个例子中,with后面跟着的get_sample()变成了Sample()。这完全没有关系,只要紧跟在with后面的语句返回的对象有 __enter__()对象和__exit__()对象即可。此例中 Sample对象的__enter__()返回的新创建的Sample对象 将其赋值个sample。由图中可以看见 type,value,trace的用途都是为了异常所用。
- python学习笔记 with语句
- Python学习小笔记with语句
- <13>python学习笔记——else语句 / with语句
- Python笔记:浅谈with语句
- Python--小甲鱼学习笔记--第34课:else语句及with语句
- python中的with-as语句学习
- python学习笔记:利用contextlib和@contextmanager实现with语句上下文实例
- python 学习笔记 if语句
- python学习笔记1语句
- Python学习笔记(条件语句)
- Python学习笔记(break语句)
- Python学习笔记(continue语句)
- 【学习笔记】python条件语句
- 【学习笔记】python循环语句
- python学习笔记之语句
- 【Python 学习手册笔记】Python 语句简介
- python with 语句研究
- python的with语句
- C++读书清单
- 安卓cpu调速器和IO策略
- 不要把自己定位的太高
- UML统一建模语言
- 快速排序C实现(阿里巴巴 2012年笔试题)
- python学习笔记 with语句
- 线段树练习 2(线段树是个啥玩意啊,还是个大师的题,我感觉青铜都不到)
- PHP数学运算和日期相关
- 伪分布式集群环境hadoop、hbase、zookeeper搭建(全)
- Python学习笔记 装饰器详解
- LeetCode:Merge k Sorted Lists
- Android中Bitmap,byte[],Drawable相互转化
- poj 2287 贪心(田忌赛马)
- excel中vba调用java程序并获取返回值