使用的基本思想大致是with所求值的對象必須有一個enter()方法和一個exit()方法。下面給一個簡單的例子去說明使用with的時候做了哪些操作
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)
1.with開始,enter()方法被執行 2.enter()方法返回的值 - 這個例子中是Foo,賦值給變量sample
3.執行代碼塊,打印變量sample的值為 Foo
4.exit()方法被調用 with真正強大之處是它可以處理異常。注意到Sample類的exit方法有三個參數- val, type 和 trace。 這些參數在異常處理中相當有用。