版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36372879/article/details/86498454
参考链接:https://blog.csdn.net/cdw_FstLst/article/details/49818461
这个语法是用来代替传统的try…finally语法的。
基本思想是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()
可以自己定义__enter__()方法和__exit__()方法进行测试:
class Sample:
def __enter__(self):
print("__enter__()方法")
return "Foo"
def __exit__(self, type, value, trace):
print("__exit__()方法")
def get_sample():
return Sample()
with get_sample() as aaa:
print(aaa)