zoukankan      html  css  js  c++  java
  • with上下文管理器

    contextlib模块中包含的工具用于处理上下文管理器和with语句

    上下文管理器由with语句启用,执行流进入with中的代码块会运行__enter__()方法,它返回在这个上下文中使用的一个对象,执行流离开with块时,则执行上下文管理的__exit__(exc_type,exc_val,exc_tb)方法,如没有发生异常,这三个参数都为None,否则,它们包含与控制流离开上下文的异常相关类型、值、和跟踪信息,例如自定义一个上下文管理

    class Context:
        def __init__(self):
            print('__init__')
        def __enter__(self):
            print('__enter__')
            return self
        def __exit__(self, exc_type, exc_val, exc_tb):
            print('__exit__')
            # print('exc_type:{},exc_val:{},exc_tb{}'.format(exc_type,exc_val,exc_tb))
    
    with Context() as c:
        print('doing work in context')
        # print(1+'1')
    
    #没有报错输出:
    __init__
    __enter__
    doing work in context
    __exit__
    报错的输出:
    class Context:
        def __init__(self):
            print('__init__')
        def __enter__(self):
            print('__enter__')
            return self
        def __exit__(self, exc_type, exc_val, exc_tb):
            print('__exit__')
            print('exc_type:{},exc_val:{},exc_tb{}'.format(exc_type,exc_val,exc_tb))
    
    with Context() as c:
        print('doing work in context')
        print(1+'1')
    
    
    
    __init__
    Traceback (most recent call last):
    __enter__
    doing work in context
      File "D:/python_project/Python之路/day01/上下文管理器.py", line 13, in <module>
    __exit__
    exc_type:<class 'TypeError'>,exc_val:unsupported operand type(s) for +: 'int' and 'str',exc_tb<traceback object at 0x00000273A4997388>
        print(1+'1')
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • 相关阅读:
    学习笔记-Java设计模式-结构型模式1
    学习笔记-Java设计原则
    阅读笔记:DQL、DML、DDL、DCL的概念与区别
    阅读笔记-HTTP返回状态码
    大数据应用技术课程实践--选题与实践方案
    15 手写数字识别-小数据集
    14 深度学习-卷积
    java集合(一)
    13-垃圾邮件分类2
    机器学习——12.朴素贝叶斯-垃圾邮件分类
  • 原文地址:https://www.cnblogs.com/superniao/p/10633494.html
Copyright © 2011-2022 走看看