Python的with和as使用方法

2021-08-19 02:56:56 字數 991 閱讀 3167

對於乙個事先需要設定事後需要清理的任務,with可以很簡潔的處理並且監控中間的異常。但是實際上它的功能完全可以用try-except-else-finally語句實現,但是with-as更加簡潔,可以看做try語句的簡化版。

非常常見的例子是檔案的開啟

同樣的功能,如果用try語句

f = open("1.txt","w")

try:

data = f.read()

finally:

f.close()

如果用with語句

with open("1.txt","w") as f:

data = f.read()

可以看出來,with語句要簡潔許多

其實實際上,所謂事前需要設定事後需要清理,指的是乙個物件有 __enter__() 和 __exit__() 方法,只有擁有這樣方法的物件才可以用with-as語句。

我們來定義乙個符合要求的物件:

class test:

def __enter__(self):

print("enter!")

def __exit__(self, type, value, trace):

print("exit!")

if __name__ == "__main__":

with test() as t:

print('yes')

輸出是

enter!

ye***it!

待**為什麼__enter__和__exit__方法的引數必須是1個和4個?

如果改變__exit__的引數數量則報錯

typeerror: __exit__() takes 3 positional arguments but 4 were given

本文參考了

python中strip和split的使用

strip 剝去,python strip 方法 python 字串 python 字串 描述 python strip 方法用於移除字串頭尾指定的字元 預設為空格 語法 strip 方法語法 str.strip chars 引數 chars 移除字串頭尾指定的字元。返回值 返回移除字串頭尾指定的字...

Python中strip和split的使用

strip 引數為空時,預設刪除開頭和結尾處的空白符,包括 n r t split 按字串 單個字元 全部分割 ipaddrx xx173.10.1.101 t n ipaddrx.strip x 刪除字串ipaddr中開頭和結尾處的x 173.10.1.101 t n ipaddrx.strip ...

python包使用 Python模組和包使用

1 什麼是模組 模組就是乙個.py的檔案 2 為什麼要使用模組?最開始的程式 沒有任何組織 函式 類 模組 包 為了讓程式的組織結構更加靈活清晰,降低耦合性 方便管理 3 如何使用模組 1 import 只能匯入在當前目錄 和內建的模組,使用模組裡的內容需要 模組.來呼叫 2 from.import...