zoukankan      html  css  js  c++  java
  • with语法

    上下文管理协议

    要使用 with 语句,首先要明白上下文管理器这一概念。有了上下文管理器,with 语句才能工作。 
    下面是一组与上下文管理器和with 语句有关的概念。 
    上下文管理协议(Context Management Protocol):包含方法 __enter__() 和 __exit__(),支持该协议的对象要实现这两个方法。 
    上下文管理器(Context Manager):支持上下文管理协议的对象,这种对象实现了__enter__() 和 __exit__() 方法。上下文管理器定义执行 with 语句时要建立的运行时上下文,负责执行 with 语句块上下文中的进入与退出操作。通常使用 with 语句调用上下文管理器,也可以通过直接调用其方法来使用。 
    运行时上下文(runtime context):由上下文管理器创建,通过上下文管理器的 __enter__() 和__exit__() 方法实现,__enter__() 方法在语句体执行之前进入运行时上下文,__exit__() 在语句体执行完后从运行时上下文退出。with 语句支持运行时上下文这一概念。 
    上下文表达式(Context Expression):with 语句中跟在关键字 with 之后的表达式,该表达式要返回一个上下文管理器对象。 
    语句体(with-body):with 语句包裹起来的代码块,在执行语句体之前会调用上下文管理器的 __enter__() 方法,执行完语句体之后会执行__exit__() 方法。

    with如何工作?

    • 紧跟with后面的语句被求值后,返回对象的 __enter__() 方法被调用,这个方法的返回值将被赋值给as后面的变量。
    • 当with后面的代码块全部被执行完之后,将调用前面返回对象的 __exit__()方法。
    class Sample:
        def __enter__(self):
            print("In __enter__()")
            return "Foo"
        def __exit__(self, type, value, trace):
            print("In __exit__()")
    def get_sample():
        return Sample()
    with get_sample() as sample:
        # 表达式返回的对象要实现__enter__与__exit__方法
        print("sample:", sample)
    
    # 打印内容
    In __enter__()
    sample: Foo
    In __exit__()
    

    with真正强大之处是它可以处理异常。

    可能你已经注意到Sample类的 __exit__ 方法有三个参数 val, type 和 trace。 这些参数在异常处理中相当有用。我们来改一下代码,看看具体如何工作的。

    _type = type
    class Sample:
        def __enter__(self):
            return self # 返回了实例自身
        def __exit__(self, type, value, trace):
            print("type:", type,_type(type)) # 类
            print("value:", value,_type(value)) # 实例
            print("trace:", trace,_type(trace))
        def do_something(self):
            bar = 1/0
            return bar + 10
    with Sample() as sample:
        sample.do_something()
    

      执行结果

    type: <class 'ZeroDivisionError'> <class 'type'>
    Traceback (most recent call last):
    value: division by zero <class 'ZeroDivisionError'>
      File "D:/python/luffy_2/test.py", line 15, in <module>
    trace: <traceback object at 0x000001E8E7BCEB88> <class 'traceback'>
        sample.do_something()
      File "D:/python/luffy_2/test.py", line 12, in do_something
        bar = 1/0
    ZeroDivisionError: division by zero

    实际上,在with后面的代码块抛出任何异常时,__exit__() 方法被执行。正如例子所示,异常抛出时,与之关联的type,value和stack trace传给 __exit__() 方法,因此抛出的ZeroDivisionError异常被打印出来了。开发库时,清理资源,关闭文件等等操作,都可以放在 __exit__ 方法当中。

    另外,__exit__ 除了用于tear things down,还可以进行异常的监控和处理,注意后几个参数。要跳过一个异常,只需要返回该函数True即可。

    更改上面代码

    _type = type
    class Sample:
        def __enter__(self):
            return self
        def __exit__(self, type, value, trace):
            print("type:", type,_type(type)) # 类
            print("value:", value,_type(value)) # 实例
            print("trace:", trace,_type(trace))
            return isinstance(value, ZeroDivisionError)
        def do_something(self):
            bar = 1/0
            return bar + 10
    with Sample() as sample:
        sample.do_something()
    

    执行结果

    type: <class 'ZeroDivisionError'> <class 'type'>
    value: division by zero <class 'ZeroDivisionError'>
    trace: <traceback object at 0x000001195FDDEBC8> <class 'traceback'>
    

      

  • 相关阅读:
    数据仓库
    HiveSQL 数据定义语言(DDL)
    HiveSQL 数据操控、查询语言(DML、DQL)
    【ASP.NET Core】Blazor+MiniAPI完成文件下载
    MySQL的WAL(WriteAhead Logging)机制
    MySQL系列 | 索引数据结构大全
    眼见为实,看看MySQL中的隐藏列
    mysql的默认隔离级别:可重复读(Repeatable Read)
    缓存淘汰算法LRU算法
    Android设计模式系列(12)SDK源码之生成器模式(建造者模式)
  • 原文地址:https://www.cnblogs.com/wwg945/p/8960675.html
Copyright © 2011-2022 走看看