pythonコンテキストマネージャのContextManagementの2つの実装方法

713 ワード

from contextlib import contextmanager

@contextmanager
def my_open(path,mode):
    f=open(path,mode)
    yield f #myopen       
    f.close()#       

with my_open('out.txt','w') as f:
    f.write("hello,the simplest context manage")
class File(object):

    def __init__(self,filePath,mode):
        f = open(filePath,mode)
        self.f = f

    def __enter__(self):
        print('enter')
        return  self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit')
        self.f.close()

with File('out.txt','w') as f:
    f.write('context manage')

enterを先に実行してexitを実行