……

with与async with

with与async with

应用场景

  • 文件的读写
  • 数据库的读写操作
  • Flask的上下文管理

上下文管理协议:当使用with语句时,解释器会自动调用enter,exit

class Sample:
    def __enter__(self):
        print('进入资源')
        return self

    def do_something(self):
        print('执行了')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('释放资源')
        
with Sample() as sample:
    sample.do_something()

进入with语句,调用__enter__,退出with语句时,调用__exit__

事实上smaple并不是sample=Sample(),而是__enter__返回的对象。如果__enter__没有return,sample将为None

async with

async with的用法和with一样,只是在内部使用__anter__和__aexit__来定义上下文。这样我们就能在上下文中使用异步编程。
后续更新

posted on 2021-04-21 18:00  Exlo  阅读(401)  评论(0编辑  收藏  举报

导航