python中 with as 用法
来源:互联网 发布:门口的野蛮人 知乎 编辑:程序博客网 时间:2024/06/06 01:04
这个语法是用来代替传统的try...finally语法的。
with EXPRESSION [ as VARIABLE] WITH-BLOCK
基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。
1. __enter__()方法被执行
2. __enter__()方法返回的值 - 这个例子中是"Foo",赋值给变量'sample'
3. 执行代码块,打印变量"sample"的值为 "Foo"
4. __exit__()方法被调用with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数- val, type 和 trace。这些参数在异常处理中相当有用。
http://www.cnblogs.com/itcomputer/articles/4601411.html
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。这些参数在异常处理中相当有用。
http://www.cnblogs.com/itcomputer/articles/4601411.html
阅读全文
0 0
- python中with as 用法
- python中 with as 用法
- python中with as 用法
- python 中 with as的用法
- python 中关于with...as的用法
- Python中with...as的用法
- python中 with...as的用法
- python with...as...用法
- python with...as用法
- python with...as...用法
- python with...as...用法
- python with as 用法
- python with as用法
- python with as 用法
- python的with...as...用法
- python with as的用法
- python with as的用法
- Python中关于with open file as 的用法
- 浙大数据结构-HuffMan Code
- 量化分析(8)——唐安奇通道
- 每周LeetCode算法题(七): 题目: 198. House Robber
- quartz
- localhost:8080和localhost:8080/应用名 报错404及project—clean与tomcat—clean区别
- python中 with as 用法
- python学习(十九)
- git fetch 和pull区别
- UVA10474查找优化
- ArrayList、Vector、HashMap、HashTable、HashSet的默认初始容量、加载因子、扩容增量
- RTAI API---Mailbox functions
- is_null,is_numeric
- 对doget和dopost区别的理解
- distinguish "list" & "array" in python