理解python的with as 语句
生活随笔
收集整理的這篇文章主要介紹了
理解python的with as 语句
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉自點擊打開鏈接
《python標準庫》上這么一句話:
with open('filename', 'wt') as f:f.write('hello, world!')我不明白為什么這樣寫,下面這篇文章對此做出了解釋
原文地址:http://python.42qu.com/11155501
------------------
With語句是什么?
Python’s with statement provides a very convenient way of dealing with the situation where you have to do a setup and teardown to make something happen. A very good example for this is the situation where you want to gain a handler to a file, read data from the file and the close the file handler. 有一些任務,可能事先需要設置,事后做清理工作。對于這種場景,Python的with語句提供了一種非常方便的處理方式。一個很好的例子是文件處理,你需要獲取一個文件句柄,從文件中讀取數據,然后關閉文件句柄。Without the with statement, one would write something along the lines of: 如果不用with語句,代碼如下:| 123 | file = open("/tmp/foo.txt")data = file.read()file.close() |
| 12345 | file = open("/tmp/foo.txt")try:????data = file.read()finally:????file.close() |
| 12 | with open("/tmp/foo.txt") as file:????data = file.read() |
with如何工作?
while this might look like magic, the way Python handles with is more clever than magic. The basic idea is that the statement after with has to evaluate an object that responds to an __enter__() as well as an __exit__() function. 這看起來充滿魔法,但不僅僅是魔法,Python對with的處理還很聰明。基本思想是with所求值的對象必須有一個__enter__()方法,一個__exit__()方法。After the statement that follows with is evaluated, the __enter__() function on the resulting object is called. The value returned by this function is assigned to the variable following as. After every statement in the block is evaluated, the __exit__() function is called. 緊跟with后面的語句被求值后,返回對象的__enter__()方法被調用,這個方法的返回值將被賦值給as后面的變量。當with后面的代碼塊全部被執行完之后,將調用前面返回對象的__exit__()方法。This can be demonstrated with the following example: 下面例子可以具體說明with如何工作:| 12345678910111213141516171819 | #!/usr/bin/env python# with_example01.pyclass 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 |
| 1234 | bash-3.2$ ./with_example01.pyIn __enter__()sample: FooIn __exit__() |
| 12345678910111213141516171819 | #!/usr/bin/env python# with_example02.pyclass 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 + 10with Sample() as sample:????sample.do_something() |
| 12345678910 | bash-3.2$ ./with_example02.pytype: <type 'exceptions.ZeroDivisionError'>value: integer division or modulo by zerotrace: <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/0ZeroDivisionError: integer division or modulo by zero |
總結
以上是生活随笔為你收集整理的理解python的with as 语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DreamWeaver下如何应用CSS样
- 下一篇: websocket python爬虫_p