with-as

with-as

  • with…as语句是简化版的try except finally语句。
  • 所谓上下文管理协议,其实是指with后面跟的expression。这个expression一般都是一个类的实体。这个类的实体里面要包含有对__enter__和__exit__函数的定义才行。

异常

    try:
        execution block  ##正常执行模块
    except A:
        exc A block ##发生A错误时执行
    except B:
        exc B block ##发生B错误时执行
    except:
        other block ##发生除了A,B错误以外的其他错误时执行
    else:
        if no exception, jump to here ##没有错误时执行
    finally:
        final block  ##总是执行

类比

    with expression [as variable]:
        with-block

    try:
        执行 __enter__的内容
        执行 with_block.
    finally:
        执行 __exit__内容

示例1

    class Sample(object):             # object类是所有类最终都会继承的类
        def __enter__(self):          # 类中函数第一个参数始终是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:
        print("sample:", sample)


    print(Sample)    # 这个表示类本身   <class '__main__.Sample'>
    print(Sample())  # 这表示创建了一个匿名实例对象 <__main__.Sample object at 0x00000259369CF550>

    # 结果
    In __enter__()
    sample: Foo
    In __exit__()
    <class '__main__.Sample'>
    <__main__.Sample object at 0x000001F4D3185A48>

示例2

    class Sample:
        def __enter__(self):
            print("In __enter__()")
            return self

        def __exit__(self, type, value, trace):
            print("type:", type)
            print("value:", value)
            print("trace:", trace)
            print("In __exit__()")

        def do_something(self):
            bar = 1 / 0
            return bar + 10


    with Sample() as sample:
        sample.do_something()

    # 结果
    In __enter__()
    type: <class 'ZeroDivisionError'>
    value: division by zero
    trace: <traceback object at 0x0000020707B95AC8>
    In __exit__()
    Traceback (most recent call last):
      File ".\test.py", line 24, in <module>
        sample.do_something()
      File ".\test.py", line 19, in do_something
        bar = 1 / 0
    ZeroDivisionError: division by zero

参考

python中with…as的用法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值