Python上下文管理器

自定义上下文管理器:需要实现__enter__ 方法和 __exit__ 方法

微信截图_20200227163024.png

class Test:
    def __enter__(self):
        print("enter")
        return "XXX "
        # return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # exc_type 异常的类型;exc_val 异常的值;exc_tb 异常的追踪信息
        print(self, exc_type, exc_val, exc_tb)

        # 提取异常信息
        import  traceback
        print(traceback.extract_tb(exc_tb))
        print("exit")

        # 返回值为True,将不在对外界抛出异常信息;如果为False或者None,将对外抛出异常信息
        return True



with Test() as T:
    print("上下文管理器的语句体")
    print(T)

    1/0


# 运行结果
enter
上下文管理器的语句体
XXX 
<__main__.Test object at 0x000001ECFBBD8400> <class 'ZeroDivisionError'> division by zero <traceback object at 0x000001ECFD86FA80>
[<FrameSummary file C:/code/python继承.py, line 25 in <module>>]
exit

contextlib 模块

@contextlib.contextmanager,使用装饰器, 让一个生成器变成一个"上下文管理器"

import contextlib

@contextlib.contextmanager
def Test():
    # yield 语句前面的代码当中 __enter__来执行;yield 语句后面的代码当作 __exit__来执行
    print(1)
    yield "XXX"
    print(2)

with Test() as T:
    print(3, T)

#代码执行
1
3 XXX
2

import contextlib

@contextlib.contextmanager
def Test():
    try:
        yield
    except ZeroDivisionError as e:
        print("error: ", e)


with Test() as T:
    1/0

#运行结果
error:  division by zero

contextlib.closing,这个函数, 让一个拥有close方法但不是上下文管理器的对象变成"上下文管理器"

class Test:

    def t(self):
        print("t函数执行")

    def close(self):
        print("释放资源")
    #
    # def __enter__(self):
    #     return self
    #
    # def __exit__(self, exc_type, exc_val, exc_tb):
    #     self.close()

import contextlib

with contextlib.closing(Test()) as T:
    T.t()

#运行结果
t函数执行
释放资源
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。