类与对象深度问题与解决技巧(3 上下文管理器)

首先写一个简单的异常处理

try:
    f = open('demo.txt', 'w')
    # 抛出异常
    raise TypeError
# 捕获异常
except TypeError as e:
    print('TypeError')
    f.close()
except ValueError as e:
    print('ValueError')
    f.close()
except Exception as e:
    print('Exception')
    f.close()
finally:
    print('end...')
# TypeError
# end...

使用上下文管理器的目的就是简化以上的操作
with open(‘demo.txt’, ‘w’) as f:
f.write()

那类可以支持上下文管理器吗?

class Sample(object):
    def __enter__(self):
        print('Start')
        return self

    def demo(self):
        print('Sample...')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(exc_type) # 异常类 <class 'AttributeError'>
        print(exc_val) # 异常值 'Sample' object has no attribute 'demos'
        print(exc_tb)  # 追踪信息,也就是在哪一行报错 <traceback object at 0x000002098C398208>
        print('ending')

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

想要类支持上下文管理器必须要有__enter__和__exit__方法

还有一种更简单的上下文管理器,通过修饰器

import contextlib


@contextlib.contextmanager
def text(name):
    print('Start...')
    yield {}
    print('Ending...')
    # yield 上面的相当于__enter__函数,下面相当于__exit__函数


with text('juren') as f:
    print('operation')
# Start...
# operation
# Ending...

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值