實(shí)現(xiàn)自定義上下文管理器
# 例如:實(shí)現(xiàn)上下文件管理器
import os
class MyDir:
def __init__(self, filename, mode):
self.__filename = filename
self.__mode = mode
def __enter__(self):
print('-----執(zhí)行enter-------------')
self.f = open(self.__filename, mode=self.__mode)
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
print('-----------執(zhí)行exit------------')
print(exc_type, exc_val, exc_tb)
self.f.close()
with MyDir('1.txt', 'r') as a:
print(a.readlines())