python with as的用法

來源:互聯網
上載者:User

標籤:建立   http   odi   value   sam   代碼塊   需要   bsp   amp   

以下為轉載https://www.cnblogs.com/DswCnblog/p/6126588.html

with。。as。。一個使用情境是檔案處理,你需要擷取一個檔案控制代碼,從檔案中讀取資料,然後關閉檔案控制代碼。

普通的檔案處理如下:

1 file = open("/tmp/foo.txt")2 data = file.read()3 file.close()#檔案使用完畢後必須關閉,因為檔案對象會佔用作業系統的資源,並且作業系統同一時間能開啟的檔案數量也是有限的

由於檔案讀寫時都有可能產生IOError,一旦出錯,後面的f.close()就不會調用。所以,為了保證無論是否出錯都能正確地關閉檔案,我們可以使用try ... finally來實現:

1 file = open("/tmp/foo.txt")2 try:3     data = file.read()4 finally:5     file.close()

但是還有一個更簡潔的實現,就是用with as

1 with open("/tmp/foo.txt") as file:2     data = file.read()

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

 1 class Sample: 2     def __enter__(self): 3         print "In __enter__()" 4         return "Foo" 5   6     def __exit__(self, type, value, trace): 7         print "In __exit__()" 8   9 def get_sample():10     return Sample()11  12 with get_sample() as sample:13     print "sample:", sample

運行如下:

1 In __enter__()2 sample: Foo3 In __exit__()

運行過程:

1. __enter__()方法被執行,返回的對象賦值給變數‘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:", type        print "value:", value        print "trace:", trace     def do_something(self):        bar = 1/0        return bar + 10 with Sample() as sample:    sample.do_something()

這個例子中,with後面的get_sample()變成了Sample()。這沒有任何關係,只要緊跟with後面的語句所返回的對象有__enter__()和__exit__()方法即可。此例中,Sample()的__enter__()方法返回新建立的Sample對象,並賦值給變數sample。

代碼執行後:

 1 bash-3.2$ ./with_example02.py 2 type: <type ‘exceptions.ZeroDivisionError‘> 3 value: integer division or modulo by zero 4 trace: <traceback object at 0x1004a8128> 5 Traceback (most recent call last): 6   File "./with_example02.py", line 19, in <module> 7     sample.do_something() 8   File "./with_example02.py", line 15, in do_something 9     bar = 1/010 ZeroDivisionError: integer division or modulo by zero

實際上,在with後面的代碼塊拋出任何異常時,__exit__()方法被執行。正如例子所示,異常拋出時,與之關聯的type,value和stack trace傳給__exit__()方法,因此拋出的ZeroDivisionError異常被列印出來了。開發庫時,清理資源,關閉檔案等等操作,都可以放在__exit__方法當中。

因此,Python的with語句是提供一個有效機制,讓代碼更簡練,同時在異常產生時,清理工作更簡單。

 

python with as的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.