日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python语言中with as的用法使用详解

發布時間:2024/9/20 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python语言中with as的用法使用详解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本篇文章主要介紹了python語言中with as的用法使用詳解,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

With語句是什么?

有一些任務,可能事先需要設置,事后做清理工作。對于這種場景,Python的with語句提供了一種非常方便的處理方式。一個很好的例子是文件處理,你需要獲取一個文件句柄,從文件中讀取數據,然后關閉文件句柄。
如果不用with語句,代碼如下:

?

1

2

3

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

data = file.read()

file.close()

這里有兩個問題。一是可能忘記關閉文件句柄;二是文件讀取數據發生異常,沒有進行任何處理。下面是處理異常的加強版本:

?

1

2

3

4

5

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

try:

??data = file.read()

finally:

??file.close()

雖然這段代碼運行良好,但是太冗長了。這時候就是with一展身手的時候了。除了有更優雅的語法,with還可以很好的處理上下文環境產生的異常。下面是with版本的代碼:

?

1

2

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

??data = file.read()

with如何工作?

這看起來充滿魔法,但不僅僅是魔法,Python對with的處理還很聰明?;舅枷胧莣ith所求值的對象必須有一個__enter__()方法,一個__exit__()方法。

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

下面例子可以具體說明with如何工作:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#!/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真正強大之處是它可以處理異常??赡苣阋呀涀⒁獾絊ample類的__exit__方法有三個參數- val, type 和 trace。 這些參數在異常處理中相當有用。我們來改一下代碼,看看具體如何工作的。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#!/usr/bin/env python

# with_example02.py

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。

代碼執行后:

bash-3.2$ ./with_example02.py
type: <type 'exceptions.ZeroDivisionError'>
value: integer division or modulo by zero
trace: <traceback object at 0x1004a8128>
Traceback (most recent call last):
? File "./with_example02.py", line 19, in <module>
??? sample.do_something()
? File "./with_example02.py", line 15, in do_something
??? bar = 1/0
ZeroDivisionError: integer division or modulo by zero

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

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

with-as語句

從python2.6開始,with就成為默認關鍵字了。With是一個控制流語句,跟if for while try之類的是一類,with可以用來簡化try-finally代碼,看起來比try finally更清晰,所以說with用很優雅的方式處理上下文環境產生的異常。with關鍵字的用法如下:

?

1

2

with expression as variable:

??with block

該代碼快的執行過程是:

1.先執行expression,然后執行該表達式返回的對象實例的__enter__函數,然后將該函數的返回值賦給as后面的變量。(注意,是將__enter__函數的返回值賦給變量)?

2.然后執行with block代碼塊,不論成功,錯誤,異常,在with block執行結束后,會執行第一步中的實例的__exit__函數

with-as語句使用舉例

(1)打開文件的例子?

with-as語句最常見的一個用法是打開文件的操作,如下:

?

1

2

with open("decorator.py") as file:

??print file.readlines()

(2)自定義?

with語句后面的對象必須要有__enter__和__exit__方法,如下是一個自定義的例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

class WithTest():

??def __init__(self,name):

????self.name = name

????pass

?

??def __enter__(self):

????print "This is enter function"

????return self

?

??def __exit__(self,e_t,e_v,t_b):

????print "Now, you are exit"

?

??def playNow(self):

????print "Now, I am playing"

?

print "**********"

with WithTest("coolboy") as test:

??print type(test)

??test.playNow()

??print test.name

print "**********"

上述代碼運行的結果如下:

**********
This is enter function
<type 'instance'>
Now, I am playing
coolboy
Now, you are exit
**********

分析以上代碼: 一二行,執行open函數,該函數返回一個文件對象的實例,然后執行了該實例的__enter__函數,該函數返回此實例本身,最后賦值給file變量。從456句可以印證。?

自定義的類WithTest,重載了__enter__和__exit__函數,就可以實現with這樣的語法了,注意在__enter__函數中,返回了self,在__exit__函數中,可以通過__exit__的返回值來指示with-block部分發生的異常是否需要reraise,如果返回false,則會reraise with block異常,如果返回ture,則就像什么也沒發生。

上下文管理器contextlib模塊對with-as的支持

contextlib 模塊提供了3個對象:裝飾器 contextmanager、函數 nested 和上下文管理器 closing。使用這些對象,可以對已有的生成器函數或者對象進行包裝,加入對上下文管理協議的支持,避免了專門編寫上下文管理器來支持 with 語句。?

以contextlib的closing來說,closing幫助實現了__enter__和__exit__方法,用戶不需要自己再實現這兩個方法,但是被closing分裝的對象必須提供close方法。contextlib.closing類的實現代碼如下:

?

1

2

3

4

5

6

7

8

class closing(object):

??# help doc here

??def __init__(self, thing):

????self.thing = thing

??def __enter__(self):

????return self.thing

??def __exit__(self, *exc_info):

????self.thing.close()

下面是一個使用contextlib.closing的例子:

?

1

2

3

4

import contextlib

request_url = ('http://www.sina.com.cn/')

with contextlib.closing(urlopen(request_url)) as response:

??return response.read().decode('utf-8')

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

來源:https://www.jb51.net/article/135285.htm

總結

以上是生活随笔為你收集整理的python语言中with as的用法使用详解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。