with...as
来源:互联网 发布:javascript and or 编辑:程序博客网 时间:2024/05/21 06:50
这个语法是用来代替传统的try…finally语法的。
with EXPRESSION [ as VARIABLE] WITH-BLOCK
基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。
紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。
- file = open(“/tmp/foo.txt”)
- try:
- data = file.read()
- finally:
- file.close()
使用with…as…的方式替换,修改后的代码是:
- with open(“/tmp/foo.txt”) as file:
- data = file.read()
- #!/usr/bin/env python
- # with_example01.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. __enter__()方法被执行
2. __enter__()方法返回的值 - 这个例子中是”Foo”,赋值给变量’sample’
3. 执行代码块,打印变量”sample”的值为 “Foo”
4. __exit__()方法被调用with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数- val, type 和 trace。这些参数在异常处理中相当有用。
阅读全文
0 0
- with as
- with as
- with as
- WITH AS
- with...as...
- WITH AS
- with...as
- WITH AS
- with as 用法
- ORACLE WITH AS 用法
- ORACLE WITH AS 用法
- with as 用法
- oracle with as
- WITH AS的用法
- With as 的用法
- WITH AS的含义
- WITH AS 用法
- with as的用法
- 1.2 dump和restore命令(备份,恢复)
- Android 反编译XML 代码乱码问题 解决
- 网络编程socket之bind、Listen 及 accept
- [沉思录(中英双语)·典藏本].(古罗马)奥勒留.扫描版.PDF 免费下载
- 赋值类型中的自动转换
- with...as
- LeetCode 70. Climbing Stairs 动态规划
- 函数返回类型和形参
- 【BZOJ2127】happiness 网络流
- Latex常用命令
- 泛型DAO
- Ubuntu更新vim编辑器,及vi常用命令
- Diffie-Hellman
- JAVA并发编程之volatile变量应用详解