python 中with的用法
来源:互联网 发布:mac终端输入密码错误 编辑:程序博客网 时间:2024/05/29 09:53
可以用with来保证关闭打开的文件
with open('hello.txt') as f:
do some file operations
在之前如果要保证关闭文件需要这样:
f = open('hello.txt')
try:
do some file operations
finally:
f.close()
为了简化这些操作,pyhton2.5中引入with,在进入with时python会自动调用对象的__enter__ 函数,
离开with时会调用 __exit__ 函数,如下所示。
class SomeThing(object):
def __enter__(self):
set things up
return self
def __exit__(self, type, value, traceback):
tear things down
with open('hello.txt') as f:
do some file operations
在之前如果要保证关闭文件需要这样:
f = open('hello.txt')
try:
do some file operations
finally:
f.close()
为了简化这些操作,pyhton2.5中引入with,在进入with时python会自动调用对象的__enter__ 函数,
离开with时会调用 __exit__ 函数,如下所示。
class SomeThing(object):
def __enter__(self):
set things up
return self
def __exit__(self, type, value, traceback):
tear things down
0 0
- python中with的用法
- python 中with的用法
- Python中With的用法
- python中with的用法
- Python中with的用法
- python中with的用法
- python 中 with as的用法
- python 中关于with...as的用法
- python中with和contextlib的用法
- Python中with...as的用法
- python中with语句的用法
- python中 with...as的用法
- python中with的简单用法
- python的with用法
- python的with用法
- python的with用法
- python的with用法
- python的with用法
- VS 2010 winform 设计器
- 基数排序----非比较型排序
- 九度OJ 1387 斐波那契数列
- Media Foundation学习笔记(四)Media Foundation的架构 Platform API
- iOS 7用户界面过渡指南
- python 中with的用法
- 什么是哈希表
- centOS目录结构详细版
- fedora 11安装 samba 全过程(yum 和源码级编译)
- oracle产品下载地址
- 多线程 - 你知道线程栈吗(私有栈)
- Java中正则表达式的一个简单例子
- ORA-01502: 索引或这类索引的分区处于不可用状态
- 解决:widonws后台运行redis-server.exe问题