python中as是什么意思_python中with python中with as 是什么意思刚入门求解释!!!
展開全部
這個(gè)語法是用來代替?zhèn)鹘y(tǒng)的try...finally語法的32313133353236313431303231363533e4b893e5b19e31333431343038。
with EXPRESSION [ as VARIABLE] WITH-BLOCK
基本思想是with所求值的對(duì)象必須有一個(gè)__enter__()方法,一個(gè)__exit__()方法。
緊跟with后面的語句被求值后,返回對(duì)象的__enter__()方法被調(diào)用,這個(gè)方法的返回值將被賦值給as后面的變量。當(dāng)with后面的代碼塊全部被執(zhí)行完之后,將調(diào)用前面返回對(duì)象的__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__()方法返回的值 - 這個(gè)例子中是"Foo",賦值給變量'sample'
3. 執(zhí)行代碼塊,打印變量"sample"的值為 "Foo"
4. __exit__()方法被調(diào)用with真正強(qiáng)大之處是它可以處理異常。可能你已經(jīng)注意到Sample類的__exit__方法有三個(gè)參數(shù)- val, type 和 trace。這些參數(shù)在異常處理中相當(dāng)有用。
請(qǐng)采納!
總結(jié)
以上是生活随笔為你收集整理的python中as是什么意思_python中with python中with as 是什么意思刚入门求解释!!!的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Silicon Labs CP210x
- 下一篇: 中望3D 2019破解补丁|中望3D 2