Home  >  Article  >  Backend Development  >  Python with的用法

Python with的用法

WBOY
WBOYOriginal
2016-06-16 08:42:341186browse

在Python中,with关键字是一个替你管理实现上下文协议对象的好东西。例如:file等。示例如下:
  

from __future__ import with_statement 
with open('cardlog.txt','r') as item : 
  for line in item : 
    print line; 

 
 在file的结束,会自动关闭该文件句柄。
 
在python2.6中,with正式成为了关键字
所以在python2.5以前,要利用with的话,需要使用:

from __future__ import with_statement 

 
 它的原理如下:
所有实现上下文协议的对象都包含以下三种方法:
__context__()  它返回一个自我管理的上下文对象,或者一个真正意义的上下文管理器
 
__enter()__  进入上下文管理器,开始迭代
 
当with语句结束的时候,无论是正常结束还是抛出异常,都会执行__exit__(),该方法用于关闭资源连接。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn