Python的with...as的用法


這個語法是用來代替傳統的try...finally語法的。 

with EXPRESSION [ as VARIABLE] WITH-BLOCK 

基本思想是with所求值的對象必須有一個__enter__()方法,一個__exit__()方法。

緊跟with后面的語句被求值后,返回對象的__enter__()方法被調用,這個方法的返回值將被賦值給as后面的變量。當with后面的代碼塊全部被執行完之后,將調用前面返回對象的__exit__()方法。

[python] view plain copy
  1. file = open("/tmp/foo.txt")  
  2. try:  
  3.     data = file.read()  
  4. finally:  
  5.     file.close()  

使用with...as...的方式替換,修改后的代碼是:

[python] view plain copy
  1. with open("/tmp/foo.txt") as file:  
  2.     data = file.read()  
[python] view plain copy
  1. #!/usr/bin/env python  
  2. # with_example01.py  
  3.    
  4.    
  5. class Sample:  
  6.     def __enter__(self):  
  7.         print "In __enter__()"  
  8.         return "Foo"  
  9.    
  10.     def __exit__(self, type, value, trace):  
  11.         print "In __exit__()"  
  12.    
  13.    
  14. def get_sample():  
  15.     return Sample()  
  16.    
  17.    
  18. with get_sample() as sample:  
  19.     print "sample:", sample  

執行結果為
[python] view plain copy
  1. In __enter__()  
  2. sample: Foo  
  3. In __exit__()  

1. __enter__()方法被執行

2. __enter__()方法返回的值 - 這個例子中是"Foo",賦值給變量'sample'

3. 執行代碼塊,打印變量"sample"的值為 "Foo"

4. __exit__()方法被調用with真正強大之處是它可以處理異常。可能你已經注意到Sample類的__exit__方法有三個參數- val, type 和 trace。這些參數在異常處理中相當有用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM