0. 上下文件管理

上下文件管理

class Foo(object):

    def __enter__(self):
        return 123

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

obj = Foo()

with obj as f:
    print(f)
123
exit
class Foo(object):

    def do_somthing(self):
        print("do something")

    def close(self):
        print("close")

# 使用context去管理Foo类的执行和关闭
class Context:
    def __enter__(self):
        self.data = Foo()
        return self.data

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.data.close()

with Context() as ctx:
    ctx.do_somthing()
do something
close