python with语句和自定义上下文管理器

with语句和自定义上下文管理器

with语句

  • with是一种上下文管理协议,with语句处理的对象有两个方法,一个是__enter__,另一个是__exit__
  • 在进入语句体之前会执行__enter__,语句体执行之后会自动执行__exit__
  • 举一个with的用法
    with open("test.txt", 'r') as f:
        infos = f.read()
    

自定义类使用上下文管理器

  • 前面已经说到了with处理的对象包含__enter____exit__,那么我们自定义的类也必须有这两个对象
  • 示例代码
    class Test(object):
        def __init__(self):
            print("初始化")
    
        def __enter__(self):
            print("enter")
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            print("exit")
    
    
    # 使用自定义的上下文管理器
    with Test() as f:
        print('语句体')
    # 输出结果
    """
    初始化
    enter
    语句体
    exit
    """
    
    

对于def __exit__(self, exc_type, exc_val, exc_tb):里面的参数是在出现异常的时候使用的

contextlib的使用

使用contextlib可以简化上下文管理器

  • 示例代码
    import contextlib
    
    
    @contextlib.contextmanager
    def file_open(filename):
        # __enter__函数
        print("open file")
        yield {}
        # __exit__函数
        print("close file")
    
    
    with file_open('role.txt') as f:
        print('operation')
    
    # 输出结果
    """
    open file
    operation
    close file
    
    """
    
    

最后,有喜欢博主写的内容的伙伴可以收藏加关注哦!

猜你喜欢

转载自blog.csdn.net/weixin_44604586/article/details/106832304
今日推荐