用法
with所求值的对象必须有一个__enter__()和__exit__()方法
with A as B:
A被执行后,A所返回的对象的__enter__()方法被执行,这个方法返回的值传给了B,当with后面的代码全部完成后,将执行A所返回的对象的__exit__()
e.g. 1
file = open("test.txt")
try:
data = file.read()
finally:
file.close()
with open("test.txt") as file:
data = file.read()
e.g. 2
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)
# result
# In __enter__()
# sample: Foo
# In __exit__()
# Notes:
# __enter__()执行后,返回的值赋给了sample,然后执行with下面的代码,执行完毕后执行__exit__()
exit()的三个参数有什么用?
class Sample():
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print("type:", type)
print("value:", value)
print("trace:", trace)
def do_something(self):
bar = 1/0
return bar + 10
with Sample() as sample:
sample.do_something()