with
来源:互联网 发布:算法问题实战策略 pdf 编辑:程序博客网 时间:2024/05/17 05:09
context manager
An object which controls the environment seen in a with statement by defining __enter__() and __exit__() methods. See PEP 343.
我们可以用dir来查看file对象,可以发现file对象中是被定义了__enter__和__exit__的,所以可以用with来使用。查看方法>>> f = open('tmp.py')
>>> dir(f)
<完>
An object which controls the environment seen in a with statement by defining __enter__() and __exit__() methods. See PEP 343.
所有具有context manager特性的对象都可以用with来简化编程。但是with有个问题就是__exit__()的调用的时间是不固定的,在小程序中一般是没有问题的,但是在大程序中可能会有不确定的bug。比较常用的是针对file对象,如下例子
with open("myfile.txt") as f: for line in f: print(line, end="")
我们可以用dir来查看file对象,可以发现file对象中是被定义了__enter__和__exit__的,所以可以用with来使用。查看方法>>> f = open('tmp.py')
>>> dir(f)
同样,我们可以定义自己的可以用with的对象,只要实现__enter__和__exit__的动作即可。
#-*- coding:utf-8 -*-class A:def __enter__(self):print('enter')#函数可以在手册中搜索__exit__看到def __exit__(self, exc_type, exc_value, traceback):print('exit')def test(self):return "I'm A"if __name__ == '__main__':with A() as a:print("OK")
<完>
0 0
- with
- with
- with
- oracle with
- oracle with
- js with
- with as
- WITH(NOLOCK)
- with as
- With (NoLock)
- WITH 查询
- with 语句
- with as
- start with
- With SqlServer
- WITH (NOLOCK)
- WITH (NOLOCK)
- WITH (NOLOCK)
- 厉害人们的真正减肥法随书光盘下载地址
- valgrind 的使用简介
- flash编程基础1----文档类路径设置
- DBUtils学习(二)
- DateTimePicker控件获取时间数据,并转化为字符串(两种方法)(2014-05-18)
- with
- spring bean的作用域
- 线段树之成段更新( 需要用到延迟标记,简单来说就是每次更新的时候不要更新到底,用延迟标记使得更新延迟到下次需要更新or询问到的时候)
- or1200构建sopc系统之软件环境搭建
- Eclipse 中Web项目如何引用Java项目源码调试的配置
- POJ 2431 Expedition
- 改变EditText边框颜色
- VS2013配置opengl
- js学习小结(十一)2014.5.15(requirejs,js开发分层,获取元素的大小)