Python中的with...as用法介紹

來源:互聯網
上載者:User

Python中的with...as用法介紹

   這篇文章主要介紹了Python中的with...as用法介紹,本文直接給出用法執行個體,需要的朋友可以參考下

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

  代碼如下:

  with EXPRESSION [ as VARIABLE] WITH-BLOCK

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

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

   代碼如下:

  file = open("/tmp/foo.txt")

  try:

  data = file.read()

  finally:

  file.close()

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

  代碼如下:

  with open("/tmp/foo.txt") as file:

  data = file.read()

  #!/usr/bin/env python

  # with_example01.py

  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

  執行結果為

   代碼如下:

  In __enter__()

  sample: Foo

  In __exit__()

  1. __enter__()方法被執行

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

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

  4. __exit__()方法被調用with真正強大之處是它可以處理異常。可能你已經注意到Sample類的__exit__方法有三個參數- val, type 和 trace。這些參數在異常處理中相當有用。我們來改一下代碼,看看具體如何工作的。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.