Python中的with...as用法介紹
這個語法是用來代替?zhèn)鹘y(tǒng)的try...finally語法的。
with EXPRESSION [ as VARIABLE] WITH-BLOCK
基本思想是with所求值的對象必須有一個__enter__()方法,一個__exit__()方法。
緊跟with后面的語句被求值后,返回對象的__enter__()方法被調(diào)用,這個方法的返回值將被賦值給as后面的變量。當with后面的代碼塊全部被執(zhí)行完之后,將調(diào)用前面返回對象的__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
執(zhí)行結(jié)果為
In __enter__()
sample: Foo
In __exit__()
1. __enter__()方法被執(zhí)行
2. __enter__()方法返回的值 - 這個例子中是"Foo",賦值給變量'sample'
3. 執(zhí)行代碼塊,打印變量"sample"的值為 "Foo"
4. __exit__()方法被調(diào)用with真正強大之處是它可以處理異常??赡苣阋呀?jīng)注意到Sample類的__exit__方法有三個參數(shù)- val, type 和 trace。這些參數(shù)在異常處理中相當有用。我們來改一下代碼,看看具體如何工作的。
相關文章
這篇文章主要為大家介紹了python中selenium模塊的安裝和配置環(huán)境變量教程、提取數(shù)據(jù)操作、無頭模式,有需要的朋友可以借鑒參考下,希望能夠?qū)Υ蠹矣兴鶐椭?/div> 2022-10-10
Python中eval()函數(shù)的功能及使用方法小結(jié)
python中eval(str)函數(shù)很強大,官方解釋為:將字符串str當成有效的表達式來求值并返回計算結(jié)果,所以,結(jié)合math當成一個計算器很好用2023-05-05最新評論

