Python在類中實現上下文管理器及優化方案

2021-10-02 16:42:31 字數 744 閱讀 1237

一,python中with語句:上下文管理協議

類中實現上下文管理器需要實現兩個方法:

1、def enter(self) (必須return self)

2、def exit(self)

如下**例項:

class a():

def_enter_(self): #開啟檔案 獲取資源

print(『start』)

return self

def opr(self):

print(『處理』)

def_exit_(self,exc_type,exc_val,exc_tb): #釋放資源

print(『end』)

with a() as a:

a.opr()

結果順序:start ,處理 ,end

二、使用contextlib簡化上下文管理器

import contextlib

@contextlib.contextmannger

def file_open():

#yield上方相當於_enter_()函式

print(『open file』)

yield{}

#yield下方相當於_exit_()函式

print()

with file_open(『test.text』) as f:

print(『file opration』)

(此處使用yield{}可以省掉類中多寫的兩個方法)

淺淡python中with的用法,上下文管理器

首先來看一段 class foo object def init self print 例項化乙個物件 def enter self print 進入 def exit self,exc type,exc val,exc tb print 退出 obj foo with obj print 正在執行...

python中with語句之安全上下文管理

with語句 with open tmp passwd as f print f.read 具體實現 class myopen object def init self,name,mode r self.name name self.mode mode def enter self 當with語句進...

淺淡python中with的用法,上下文管理器

首先來看一段 class foo object def init self print 例項化乙個物件 def enter self print 進入 def exit self,exc type,exc val,exc tb print 退出 obj foo with obj print 正在執行...