with 上下文管理器

import contextlib
class MyWith:
    def __enter__(self):
        print('enter')
        return self
    def doThing(self):
        print('do.....')
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit')

with MyWith() as myw:
    myw.doThing()
# enter
# do.....
# exit
@contextlib.contextmanager
def dowith(filename):
    print('start')
    yield {}
    print('end')

with dowith('aa.txt') as dow:
    print('do something....')
# start
# do something....
# end

  

posted @ 2024-01-17 12:00  howhy  阅读(1)  评论(0编辑  收藏  举报