Python的with...as的用法
__enter__()
<class 'int'>
sample: 1111111111
这个语法是用来代替传统的try...finally语法的。
with EXPRESSION [ as VARIABLE] WITH-BLOCK基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。
紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。例子:
f = open("D://report_data2.txt")
try:
data = f.read()
except:
print("读取文件失败!")
else:
print(data)
finally:
f.close()
# with...as...
with open("D://report_data2.txt") as f:
data = f.read()
print(data)
使用with...as...的方式替换,修改后的代码是:with open("D://report_data2.txt") as f:
data = f.read()
print(data)
进一步说明:
class Sample:
def __enter__(self):
print("__enter__()")
return 1111111111
def __exit__(self, type, value, trace):
print("__exit__()")
# 实例化
with Sample() as s:
print(type(s))
print("sample:", s)
执行结果为
__enter__()
<class 'int'>
sample: 1111111111
__exit__()
说明:
1. __enter__()方法被执行
2. __enter__()方法返回的值 - 这个例子中是int 1111111111,赋值给s变量
3. 执行代码块,打印变量s的值为 11111111
4. __exit__()方法被调用with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数- val, type 和 trace。这些参数在异常处理中相当有用。
收藏:https://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/