標籤:enter finally file trace try final 對象 參數 nal
with語句:
事後做清理工作。比如檔案處理,需要擷取一個檔案控制代碼,從檔案中讀取資料,然後關閉檔案控制代碼
不用with語句,代碼如下:
file = open("/tmp/foo.txt")data = file.read()file.close()
這裡有兩個問題。一是忘記關閉檔案控制代碼;二是檔案讀取資料發生異常,沒進行任何處理。下面是處理異常的加強版:
file = open("/tmp/foo.txt")try: data = file.read()finally: file.close()
這段代碼運行良好,但是太冗長。
with可以處理上下文環境產生的異常,代碼如下:
with open ("/tmp/foo.txt") as file: data = file.read()
with如何工作:
基本思想是with所求值的對象必須有一個__enter__()方法,一個__exit()__方法。
緊跟with後面的語句被求值後,返回對象的__enter__()方法被調用,這個方法的傳回值被賦值給as後面的變數。當with後面的代碼塊全部被執行完之後,將調用前面返回對象的__exit()__方法。
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)
正如你看到的:
1.__enter__()方法被執行
2.__enter__()方法返回的值---例子中是"Foo",賦值給變數“sample”
3.執行代碼塊,列印變數“sample”的值為"Foo"
4.__exit__()方法被調用
with真正強大之處是它可以處理異常。可能你已經注意到Sample類的__exit__方法有三個參數val, type, trace。這些參數在處理異常中非常有用。下面改一下代碼,看看具體如何工作。
class Sample: def __enter__(self): return self def __exit__(self, type, value, trace): print("type")
python with as 的用法